2013-01-09 64 views
1

@interface MyClass如何在iOS中初始化整数?

定义

@property (nonatomic, assign) int currentUserNum; 
@property (nonatomic, assign) BOOL isAlive; 

@implementation MyClass

@synthesize currentUserNum, isAlive; 
-(id) init { 
    if (self = [super init]) { 
    self.currentUserNum = 0; 
    self.isAlive = YES; 
    } 
    return self; 
} 

self.currentUserNum = 0;被撞坏定义-init方法,但self.isAlive = YES;可以工作!他们都是assign财产。

我想知道为什么?谢谢!

+1

在init中,为什么在调用[super init]之后没有返回self? –

+0

对不起,我有超级方法 – why

+0

应用程序崩溃时出现什么错误? – rmaddy

回答

5

您的init方法缺少很多重要的代码。

- (id)init { 
    if ((self = [super init])) { 
     _currentUserNum = 0; // it's not wise to reference properties in the init method 
    } 

    return self; 
} 

每个init方法应该遵循这个基本模式。您指定self调用适当的super init或其他self init的值。如果这不是nil,则执行相应的初始化代码,最后返回self

+0

对不起,我有超级方法并更新我的问题。还有一个问题:'_currentUserNum = 0' =='currentUserNum = 0'?你知道,我已经定义了@synthesize currentUserNum;' – why

+0

根据编译器和你的@synthesize,ivar将被命名为'currentUserNum'或'_currentUserNum'。一个会编译,一个不会。 – rmaddy

+0

感谢您的回答,我想我需要更新我的问题,请再检查一次! – why