我是这个objective-c属性属性的新手。这是代码:
student.h
#import <Foundation/NSObject.h>
@interface Student: NSObject
@property int age(assign, readwrite); //I don't know what attribute it should have
@property NSString *name(retain, readwrite); //this one either
-(Student*) initWithName: (NSString *) n andAge:(int) a;
-(void) speakName;
+(void) smoke:(NSString*) thing;
@end
student.m
#import "student.h"
@implementation Student
-(Student*) initWithName:(NSString*) n andAge:(int) a {
self = [super init];
if(self) {
[self setName: n];
[self setAge: a];
}
return self;
}
-(void) speakName {
NSLog(@"MyName is %@", _name);
}
+(void) smoke:(NSString*) thing {
NSLog(@"Smoking %@", thing);
}
@end
的main.m
#import <Foundation/Foundation.h>
#import "student.h"
int main(void) {
Student *student = [[Student alloc] initWithName: @"Markson" andAge: 29];
[student speakName];
[Student smoke:@"weed"];
[student release];
return 0;
}
为行
@property int age(assign, readwrite); //I don't know what attribute it should have
@property NSString *name(retain, readwrite); //this one either
当我不给他们任何东西时,编译器会给我4个警告:
In file included from student.m:1:
./student.h:5:1: warning: no 'assign', 'retain', or 'copy' attribute is
specified - 'assign' is assumed [-Wobjc-property-no-attribute]
@property NSString *name;
^
./student.h:5:1: warning: default property attribute 'assign' not appropriate
for non-GC object [-Wobjc-property-no-attribute]
2 warnings generated.
In file included from main.m:2:
./student.h:5:1: warning: no 'assign', 'retain', or 'copy' attribute is
specified - 'assign' is assumed [-Wobjc-property-no-attribute]
@property NSString *name;
^
./student.h:5:1: warning: default property attribute 'assign' not appropriate
for non-GC object [-Wobjc-property-no-attribute]
2 warnings generated.
请问任何人都可以知道年龄和名称属性应该使用哪些属性?
答案 0 :(得分:1)
将这些行更改为:
@property (assign, nonatomic) int age;
@property (retain, nonatomic) NSString *name;
readwrite
是默认设置,因此您无需进行设置。
查看此文档:
答案 1 :(得分:1)
@property int age(assign, readwrite); //I don't know what attribute it should have
@property NSString *name(retain, readwrite); //this one either
简短说明:
如果要为int
,float
,BOOL
等原始类型创建属性,请使用assign
如果您想保留该值,请使用strong
或retain
。
在所有其他情况下,您可以使用weak
。
始终使用atomic
,语法就像这样
@property (<assign/retain/weak>, <atomic/nonatomic>, <read/readwrite>) <dataType> <propertyName>;