2012-06-19 31 views
0

我有以下簡單的類定義:目標C類屬性變量

//mycommon.h

@interface CurrentPath : NSObject 
@property (nonatomic, strong) NSString* PathString; 
@property (nonatomic, strong) NSMutableArray* PathArr; 
- (void) addAddressToPath:(NSString*) address; 
@end 

//mycommon.m

@implementation CurrentPath : NSObject 

@synthesize PathString; 
@synthesize PathArr; 

- (void) addAddressToPath:(NSString*) address{ 
    NSLog(@"addAddressToPath..."); 

    // Add to string 
    self.PathString = [self.PathString stringByAppendingString:address]; 

    // Add to Arr 
    [self.PathArr addObject:address]; 
} 

@end 

在另一類我做#import<mycommon.h>並聲明像這樣的變量:

@interface myDetailViewController : 
{ 
     CurrentPath* currentPath; 
} 
- (void) mymethod; 
    @end 

@implementation myDetailViewController 

- void mymethod{ 
self->currentPath = [[CurrentPath alloc] init]; 
NSString* stateSelected = @"simple"; 
    [self->currentPath addAddressToPath:stateSelected]; 
} 
@end 

問題是,自我的PathString和PathArr性能> currentPath此方法調用,我認爲應該有「簡單」,在他們之後是空的。請幫忙!

+0

你在哪裏分配內存到PathArr? – rishi

+0

hmm。我認爲@synthesize應該這樣做。可以說,它並不是實例函數addAddressToPath應該填充PathString。但是當我嘗試在方法調用後打印它時,它會打印出null。不應該是「簡單」。 – shaffooo

+0

不@synthesize不會那樣做,您需要首先檢查合成生成的內存管理規則和定義。 – rishi

回答

0

當您的CurrentPath對象被創建時,您必須確保您的NSStringNSMutableArray屬性已初始化。否則,致電stringByAppendingString將導致nil,因爲它被髮送到nil對象。

一個可行的辦法或許應該

self.currentPath = [NSString string]; 
// or 
self.currentPath = @""; 
[self.currentPath addAddressToPath:@"simple"]; 

更優雅和強大的是檢查在addAddressToPath方法的nil屬性。這是跟着Objective-C的約定,並使用以小寫字母開頭的屬性名稱

if (!self.pathString) self.pathString = [NSString string]; 
if (!self.pathArr) self.pathArr = [NSMutableArray array]; 

通知。

+0

爲true。那麼pathArr呢?我在** addAddressToPath **函數中做了一個'[self.pathArr addObject:address];'但是數組的大小沒有改變。 「簡單」不會添加到Arr中。 – shaffooo

+0

完全一樣的說法。將編輯答案爲他人的利益。 – Mundi