1.类与对象(续)
1.1方法
1.1.1实例方法
1.1.1.1是以减号开头的方法(都是实例方法)
1.1.1.2用对象来调用
1.1.1.3在函数体中可以使用指针self
1.1.2类方法
1.1.2.1是以加号开头的方法
1.1.2.2用类名来调用
TRExample *e = [[TRExample alloc]init];
[e instanceMethod];
//[e classMethod];//对象不能调用类方法
[TRExample classMethod];//类方法只能使用类名调用
1.1.2.3在(类)函数体中指针self 不能被使用,原因是类方法由类名来调用,self指针指向调用那个方法的对象,这样就没有对象可指向。
TRExample.m
#import "TRExample.h"
@implementation TRExample
-(void)instanceMethod
{
NSLog(@"这是一个实例方法,%@",self.content);
}
+(void)classMethod
{
NSLog(@"这是一个类方法");
//NSLog(@"这是一个类方法,%@",self.content);//self在类方法中不能使用,原因是类方法由类名来调用,self指针指向调用那个方法的对象,这样就没有对象可指向。
}
1.1.2.4应用:工厂方法
1.1.2.4.1工厂方法用于生成类的对象
1.1.2.4.2无参工厂方法
1.1.2.4.3带参工厂方法
1.1.2.4.4特例:单例模式
1.1.2.4.4.1是一种特殊的工厂方法
1.1.2.4.4.2特殊在只能生成一个对象
单例模式例子
TRSingleton.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TRSingleton : NSObject
+(id)sharedSingleton;//单例模式的方法名以shared开头,后面跟着没有前缀的类名singleton
@end
NS_ASSUME_NONNULL_END
TRSingleton.m
#import "TRSingleton.h"
@implementation TRSingleton
+(id)sharedSingleton
{
static TRSingleton *single = nil;
if(single == nil)
{
single = [[TRSingleton alloc] init];
}
return single;
}
@end
ViewController.m
#import "ViewController.h"
#import "TRSingleton.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *outputLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
TRSingleton *s1 = [TRSingleton sharedSingleton];
TRSingleton *s2 = [TRSingleton sharedSingleton];
TRSingleton *s3 = [TRSingleton sharedSingleton];
self.outputLabel.text = [NSString stringWithFormat:@"%p\n%p\n%p",s1,s2,s3];
}
CMD+F替换
![](https://img.haomeiwen.com/i13471358/c3ebc9e075967142.png)
网友评论