2012-02-09 49 views
2

我想存儲2個整數的元組和一個NSArray中的字符。 是否有一個easyer方法比聲明一個持有2個整數和char的類?存儲2個整數的元組和一個NSArray中的字符,

我嘗試了這種方式,它工作,但它似乎相當複雜的我。有更好的和easyer的方式嗎?

@interface Container : NSObject 
@property NSInteger a; 
@property NSInteger b; 
@property char  c; 
@end 

@implementation Container 
@synthesize a = _a; 
@synthesize b = _b; 
@synthesize c = _c; 

-(Container*) initWitha:(NSInteger) a andB:(NSInteger) b andC: (char) c 
{ 
    if ((self = [super init])) { 
     self.a = a; 
     self.b = b; 
     self.c = c; 
    } 
    return self; 
} 
@end 

... 
//usage 

NSMutableArray *array = [[NSMutableArray alloc] init]; 
[array addObject: [[Container alloc] initWitha:5 andB:6 andC:'D']]; 

感謝

+1

你的init方法將需要'如果((超= [超級的init]))' – Jasarien 2012-02-09 12:12:02

+0

的NSArray只能容納對象,所以最好的辦法是創建一個C數組 – Eimantas 2012-02-09 12:12:21

回答

5

也許你可以只使用一個C結構?

struct Container { 
    NSInteger a; // If you're using char c, why not use int a? 
    NSInteger b; 
    char c; 
}; 

,那麼你可以做這樣的事情

struct Container c; 

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1] 

// Insert 
[array addObject:[NSValue value:&c withObjCType:@encode(struct Container)]]; 

// Retrieve: 
struct Container c; 
[[array objectAtIndex:i] getValue:&c]; 
1

蘋果建議您不要評價的同時建設者self爲它指定[super init]

你的init方法將需要閱讀:

-(Container *) initWitha:(NSInteger) a andB:(NSInteger) b andC: (char) c 
{ 
    self = [super init]; 

    if (self != nil) { 
     self.a =a; 
     self.b=b; 
     self.c=c; 
    } 

    return self; 
} 
+1

你會碰巧有一個鏈接到它在文檔中說的這個地方嗎? – 2014-06-03 21:05:55

+0

[此文檔](https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/Initialization/Initialization.html)給出了一個與您的陳述相矛盾的例子。 – 2016-04-27 12:25:43

+0

如果你想應用好的做法,那麼_guarding_優於嵌套:'if(!(self = [super init])){return nil; } _a = a; _b = b; _c = c;迴歸自我;'。另外,ObjC中的方法名應該是'initWithA:b:c:'。 – 2016-04-27 12:29:12

相關問題