目标C:为什么NSUInteger上的接收器类型无效而非NSString,而创建方式相同

时间:2010-12-05 11:58:12

标签: iphone objective-c

我已经为所有字段自动生成了这个源代码,为什么编译器告诉我NSUInteger上的Invalid Receiver类型而不是NSString,而创建方式相同:

/**
 class to represent an Person
 */
@interface Person: NSObject {
    // private members
    NSString* _firstName;
    NSString* _lastName;
    NSUInteger _age;
}
// Initializers
/**
 Initializes a new instance of the Person class.
 @returns a newly initialized object
 */
- (id)initPerson;

/**
 Initializes a new instance of the Person class with
 @param firstName The First Name
 @param lastName The Last Name
 @param age The Age
 @returns a newly initialized object
 */
- (id)initPersonWithFirstName:(NSString*)firstName LastName:(NSString*)lastName Age:(NSUInteger)age;

// public accessors
- (NSString*) firstName;
- (void) setFirstName: (NSString*)input;
- (NSString*) lastName;
- (void) setLastName: (NSString*)input;
- (NSUInteger) age;
- (void) setAge: (NSUInteger)input;
@end

@implementation Person
// Initializers
/**
 Initializes a new instance of the Person class.
 @returns a newly initialized object
 */
- (id)initPerson {
    if ( self = [super init] ) {
    }
    return self;
}

/**
 Initializes a new instance of the Person class with
 @param firstName The First Name
 @param lastName The Last Name
 @param age The Age
 @returns a newly initialized object
 */
- (id)initPersonWithFirstName:(NSString*)firstName LastName:(NSString*)lastName Age:(NSUInteger)age {
    if ( self = [super init] ) {
        [self setFirstName:firstName];
        [self setLastName:lastName];
        [self setAge:age];
    }
    return self;
}

// public accessors
- (NSString*) firstName {
    return _firstName;
}
- (void) setFirstName: (NSString*)input {
    [_firstName autorelease];
    _firstName = [input retain];
}
- (NSString*) lastName {
    return _lastName;
}
- (void) setLastName: (NSString*)input {
    [_lastName autorelease];
    _lastName = [input retain];
}
- (NSUInteger) age {
    return _age;
}
- (void) setAge: (NSUInteger)input {
    [_age autorelease];
    _age = [input retain];
}
@end

1 个答案:

答案 0 :(得分:8)

NSUInteger是数字类型,而不是对象。你不能向它发送消息,也不需要内存管理(除非你在堆上malloc,这是一个不同的过程,无论如何都不相关。)

如果您确实希望对象类型保存数值 - 您几乎肯定不会 - 使用NSNumber。否则,只需像对待intfloat一样对待它。即:

- (void) setAge: (NSUInteger)input {
    _age = input;
}