我用this簡單的教程來創建我的單例類。一切正常。有一兩件事不會在本教程中說,如何在這個類的方法,所以我可以從其他類訪問這些文件(例如,其它ViewControllers或AppDelegate的。)另一個類的調用方法(例如通過單例類)?
我該怎麼辦呢? 非常感謝!
我用this簡單的教程來創建我的單例類。一切正常。有一兩件事不會在本教程中說,如何在這個類的方法,所以我可以從其他類訪問這些文件(例如,其它ViewControllers或AppDelegate的。)另一個類的調用方法(例如通過單例類)?
我該怎麼辦呢? 非常感謝!
您將像定義任何其他Objective-C文件一樣定義方法。爲公共方法的頭添加一個定義,然後在實現(.m)文件中實現它們。
#import <foundation/Foundation.h>
@interface MyManager : NSObject {
NSString *someProperty;
}
@property (nonatomic, retain) NSString *someProperty;
+ (id)sharedManager;
//Add instance methods for your singleton here
- (void)someSingletonMethod;
@end
用法:
[[MyManager sharedManager] someSingletonMethod];
單.h文件中
#import <Foundation/Foundation.h>
@interface SingleTon : NSObject
{
NSString *sum;
}
+(SingleTon *) createSingleTon;
-(NSString *) sumOfTwoNumbers:(NSString *) numOne :(NSString *)numTwo;
@end
單.m文件
#import "SingleTon.h"
@implementation SingleTon
+(SingleTon *) createSingleTon
{
static SingleTon *single= nil;
if (single == nil) {
single = [[SingleTon alloc] init];
}
return single;
}
-(NSString *) sumOfTwoNumbers:(NSString *) numOne :(NSString *)numTwo
{
sum = [NSString stringWithFormat:@"%d",[numOne intValue] + [numTwo intValue]];
return sum;
}
@end
viecontroller.h文件
#import <UIKit/UIKit.h>
#import "SingleTon.h"
@interface ViewController : UIViewController
{
SingleTon *sing;
IBOutlet UITextField *one,*two,*sum;
}
-(IBAction)sum:(id)sender;
@end
viecontroller.m文件
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
sing = [SingleTon createSingleTon];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sum:(id)sender
{
sum.text = [sing sumOfTwoNumbers:one.text :two.text];
}
@end
O/P
讓你這樣一流的一類方法。也在.h文件中聲明它。
+(FFMainVC *)sharedSingleton
{
static FFMainVC *instance = nil;
if(instance == nil)
instance = [[FFMainVC alloc]init];
return instance;
}
// write your method that you wants to access from other class. also declare this in .h as well
-(void)showCartView
{
// Your Code
}
// make call of your method from second class like this
[[FFMainVC sharedSingleton]showCartView];
工作就像一個魅力!非常感謝! –