#import <Cocoa/Cocoa.h>
@interface Student : NSObject {
NSString *name;
NSString *studentNO;
}
- (NSString*)name;
- (NSString*)studentNO;
- (void)setName:(NSString*)aName;
- (void)setStudentNO:(NSString*)aStudentNO;
@end
// Student.h
- (NSString*)name
{
return name;
}
- (NSString*)studentNO
{
return studentNO;
}
- (void)setName:(NSString*)aName
{
[name autorelease];
name = [aName copy];
}
- (void)setStudentNO:(NSString*)aStudentNO
{
[studentNO autorelease];
studentNO = [aStudentNO copy];
}
main裏面這麼用:
Student *hayes = [[Student alloc] init];
[hayes setName:@"Hayes"];
[hayes setStudentNO:@"00000"];
NSLog(@"Name: %@", [hayes name]);
NSLog(@"Student NO: %@", [hayes studentNO]);
#import <Cocoa/Cocoa.h>
@interface Student : NSObject <NSCoding> {
NSString *name;
NSString *studentNO;
}
@property(copy) NSString *name;
@property(copy) NSString *studentNO;
@end
// Student.m
#import "Student.h"
@implementation Student
@synthesize name;
@synthesize studentNO;
@end
在main函數裏可以這麼調用:
Student *hayes = [[Student alloc] init];
hayes.name = @"hayes";
hayes.studentNO = @"00001";
NSLog(@"%@", hayes.name);
NSLog(@"%@", hayes. studentNO);
- - (void)setName:(NSString *)newName {
- if (name != newName) {
- [name release];
- name = [newName retain];
- // name’s retain count has been bumped up by 1
- }
- }
比如一個NSString 對象,地址爲0×1111 ,內容爲@”STR”
Copy 到另外一個NSString 之後,地址爲0×2222 ,內容相同,新的對象retain爲1 ,舊有對象沒有變化
retain 到另外一個NSString 之後,地址相同(建立一個指針,指針拷貝),內容當然相同,這個對象的retain值+1
retain 是指針拷貝,copy 是內容拷貝
下面分享一個網友的總結
一直以來個人覺得如果一個類是的property是readonly的那麼再指定其他的如assign/retain/copy這樣的屬性就實在是沒有什麼意義了。確實你想想既然都readonly了,肯定是沒有setter的,既然沒有setter那麼談assign/retain/copy又有什麼意義呢?所以一直以來我從來不對readonly的property加retain/copy屬性申明,默認assign就足夠了,simple is beautiful!
但是我現在發現我錯了,其實一直都有一種這種感覺,只是沒有找到100%的充分理由爲readonly加上retain/copy。但是假如你要在你的subclass改寫property,而加入你要改寫的是一個NSString,你像把這個屬性設置爲readwrite和copy,往往杯具就發生了,編譯時候可惡的warning 產生了,因爲copy和之前默認的assign明顯不相同啊!
終上,不論什麼時候,都要爲你的readonly的對象屬性加上合適的retain/copy申明。你現在不用,但不說明你將來就不會用,出來混遲早都要還的!