------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
1,点语法举例
#import <Foundation/Foundation.h>
//声明Stu类
@interface Stu : NSObject
{
int _age;
}
- (void) setAge:(int)age;
- (int) age;
@end
//实现Stu类
@implementation Stu
- (void)setAge:(int)age
{
_age = age;
}
- (int) age
{
return _age;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Person *stu = [[Stu alloc] init];
stu.age = 21;//点语法,等效与[stu setAge:21];
int age=stu.age;等效与int age = [stu age]
SLog(@"age is %i",age );
[stu release]
}
}
2,点语法本质
点语法的本质是方法的调用,而不是访问成员变量,当使用点语法时,编译器会自动展开成相应的方法。切记点语法的本质是转换成相应的set和get方法,如果没有set和get方法,则不能使用点语法。
3,@property和@synthesize
@property: 用在@inteface中,可用来自动生成setter和getter的声明
@synthesize:用在@implementation中,用来自动生成setter和getter的实现
@synthesize:用在@implementation中,用来自动生成setter和getter的实现
4,@property和@synthesize举例
//声明Stu类
@interface Stu : NSObject
{
int _age;
}
@property int age;
@end
//实现Stu类
@implementation Stu
@synthesize age = _age
@end
与上例相比,声明部分:
@property int age;
代替了
- (void)setAge:(int)age;
- (int)age;
实现部分:
@synthesize age = _age
代替了
- (void)setAge:(int)age
{
_age = age;
}
- (int) age
{
return _age;
}
5,@property和@synthesize使用注意
1)@synthesize age = _age;
setter和getter实现中会访问成员变量_age ,如果成员变量_age不存在,就会自动生成一个@private的成员变量_age
2)手动实现
若手动实现了setter方法,编译器就只会自动生成getter方法;若手动实现了getter方法,编译器就只会自动生成setter方法;若同时手动实现了setter和getter方法,编译器就不会自动生成不存在的成员变量
setter和getter实现中会访问成员变量_age ,如果成员变量_age不存在,就会自动生成一个@private的成员变量_age
2)手动实现
若手动实现了setter方法,编译器就只会自动生成getter方法;若手动实现了getter方法,编译器就只会自动生成setter方法;若同时手动实现了setter和getter方法,编译器就不会自动生成不存在的成员变量
6,构造方法
主要分为两步:分配内存(+alloc)和初始化(-init)
1)分配内存
1)分配内存
Stu *p1 = [Stu alloc];
Stu *p1 = [p1 init];
可以合成:
Stu *p = [[Stu alloc] init];
2)init方法的重写
- (id)init
{
// 1.一定要调用回super的init方法:初始化父类中声明的一些成员变量和其他属性
self = [super init]; // 当前对象 self
// 2.如果对象初始化成功,才有必要进行接下来的初始化
if (self != nil)
{
// 初始化成功
_age = 10;
}
// 3.返回一个已经初始化完毕的对象
return self;
}
3)自定义构造函数
- (id)initWithAge:(int)age
{
if (self = [super init])
{
_age = age;
}
return self;
}
7,分类
1)作用:通过分类(category)可以以模块的方式向现有的类添加方法。它提供了一种简单的方式,用它可以将类的定义模块化到相关方法的组或分类中。它还提供了扩展现有类定义的简便方式,并且不必访问类的源代码,也无需创建子类。
2)格式:
2)格式:
@interface 类名 (分类名称)
// 方法声明
@end
分类的实现
@implementation 类名 (分类名称)
// 方法实现
@end
3)使用注意:
(1)分类只能增加方法,不能增加成员变量
(2)分类方法实现中可以访问原来类中声明的成员变量
(3)分类可以重新实现原来类中的方法,但是会覆盖掉原来的方法,会导致原来的方法没法再使用
(4)方法调用的优先级:分类(最后参与编译的分类优先) --> 原来类 --> 父类
4)举例
#import <Foundation/Foundation.h>
//shuzi分类声明
@interface NSString (shuzi)
- (int)countshuziOfString; //计算字符串中数字的个数
@end
//分类实现
@implementation NSString (shuzi)
- (int)countshuziOfString
{
int count = 0;
for(int i = 0; i < self.length; i++)
{
char c = [selfcharacterAtIndex:i];
if (c <= 9 && c => 1)
count++;
}
return count;
}