2012-10-20 73 views
0

我用下面的代碼來定義我的C陣列(除警告偉大的工程):數組c與財產的目標C

上的.h文件:

@interface memory : NSObject 
{ 
    int places[60]; 
    int lastRecordSound; 
} 

@property int *places; 

然後我.m我不是同步它(和它的作品),但如果我嘗試同步它喜歡:

@synthesize places; 

我得到錯誤:

type of preperty "places does not match type of ivar places (int[60]) 

,如果沒有,我得到WARNNING:

auto synthesized property places will be use synthesized instance variable _places... 

那麼,什麼是定義該C數組的最佳方式?(是的,我需要ç..)

+0

'@ synchronized'和'@ synthesize'是兩個不同的關鍵字。 – 2012-10-20 10:45:59

+0

我的意思是綜合!對不起 – user1280535

回答

0

代替

@synchronize地方;

你必須寫

@synthesize地方;

而且從int places[60];改變伊娃到int *places;甚至可以完全刪除這些行。

+0

它是從頭開始合成的,是我的錯。他並不需要綜合也.. – user1280535

+0

也刪除這條線或改變它的地方,會給我這麼多的錯誤,所以它不是這樣。 – user1280535

+0

我曾嘗試以相同的方式聲明它在我的代碼中的工作,請您在此處將您的代碼複製到您要訪問的位置數組中。 –

0

This? (非ARC)

#import <Foundation/Foundation.h> 

@interface Memory:NSObject 
@property int *places; 
@end 

@implementation Memory 
@synthesize places; 
@end 

int main(int argc, char *argv[]) { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    int *p; 
    if(p = malloc(60 * sizeof(int))) { 
     p[1] = 99; 
     Memory *aMemory = [[Memory alloc] init]; 
     aMemory.places = p; 

     int *q = aMemory.places; 
     printf("q[1] = %d\n",q[1]); 

     free(p); 
     [aMemory release]; 
    } 
    else { 
     printf("ERROR: unable to malloc p\n"); 
    } 

    [pool release]; 
} 

打印q[1] = 99到控制檯。

0

自動生成的存取器函數無法將int *屬性與int[]數組關聯。但是,如果你申報財產作爲

@property(readonly) int *places; 
在.h文件中

,並提供您的.m文件自定義getter函數

- (int *)places 
{ 
    return self->places; 
} 

它的工作原理。

現在,你可以通過屬性訪問數組:

memory *mem = [[memory alloc] init]; 
mem.places[23] = 12; 

當然,編譯器不知道該數組只有60個元素,因此,如果您分配

你不會得到一個編譯器警告
mem.places[999] = 12; 

和一切不好都可能發生。

將屬性聲明爲read-only是有意義的,因爲您無法更改int數組的地址。 (如果您不需要同步訪問,您也可以將nonatomic添加到屬性屬性,但這是一個不同的主題。)