2013-01-09 62 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