码迷,mamicode.com
首页 > 移动开发 > 详细

iOS:不同属性声明方式的解析

时间:2014-09-04 00:09:57      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   div   代码   sp   

代码:

/*

属性声明方式说明:
 
----------------------- 1
@interface ...
{
    id name
}
@end
 
这样声明的属性其实可以认为是private属性,因为它只能在方法里通过name引用,外部无法通过“object.name”的方式进行引用 (内部也不能通过self引用)

----------------------  2

@interface ...
@property id name
@end

这样声明的属性可以认为是public属性,内部通过“self.name”引用;外部通过“object.name”引用
 
----------------------- 3
@implementation ...
@synthesize name
@end
 
允许以property声明的属性,在内部方法里除了以self引用外,还可以用属性名直接引用
 
----------------------- 4

self.name
其实是是两个方法(setter,getter):

id value = [self name]
[self setName = ...]
 
----------------------- 5

总结:
如果框架依赖的属性是@property,就不能实现为私有,否则程序可以崩掉
 
*/

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
    NSString *name;
}

@property NSString *address;

-(void) toString;

@end

@implementation Student

@synthesize address;

-(Student *)init
{
    name = @"lishujun";
    self.address = @"beijing";
    return self;
}

-(void) toString
{
    NSLog(@"%@ %@", name, [self address]);
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Student *student = [[Student alloc]init];
        [student toString];
        [student setAddress:@"tongzhou"];
        [student toString];
        NSLog(@"%@", student.address);
        
        // 语法错误,没有setName这个方法
        //[student setName:@"shujunli"];
        //[student toString];
        
    }
    return 0;
}

 

iOS:不同属性声明方式的解析

标签:style   blog   color   os   io   ar   div   代码   sp   

原文地址:http://www.cnblogs.com/code-style/p/3955031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!