0

我有以下简单的类定义:

//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

问题是 self->currentPath 的 PathString 和 PathArr 属性在此方法调用后为空,我认为其中应该包含“简单”。请帮忙!

4

1 回答 1

0

您必须确保在创建对象时初始化您的NSStringNSMutableArray属性CurrentPath。否则,调用stringByAppendingString将导致nil因为它被发送到一个nil对象。

一种可行的方法可能是

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

更优雅和健壮的方法是检查addAddressToPath方法中的 nil 属性。

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

Notice that am following the objective-c convention and use property names that start with lower case letters.

于 2012-06-19T07:52:31.523 回答