我使用this简单教程来创建我的单例类。一切正常。有一件事在教程中没有说,如何在该类中创建方法,所以我可以从其他类(例如其他ViewControllers或AppDelegate)访问它们。
我该怎么办? 非常感谢提前!
答案 0 :(得分:5)
您将像在任何其他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];
答案 1 :(得分:1)
singleton .h文件
#import <Foundation/Foundation.h>
@interface SingleTon : NSObject
{
NSString *sum;
}
+(SingleTon *) createSingleTon;
-(NSString *) sumOfTwoNumbers:(NSString *) numOne :(NSString *)numTwo;
@end
singleton .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
答案 2 :(得分:0)
为你的第一堂课制作一个类方法。也在.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];