我正在关注“你的第二个 iOS 应用程序”,我决定使用代码来很好地理解 Objective C ......
我要做的只是将一个对象添加到类中的可变数组中。以下是课程:
BirdSighting.h
#import <Foundation/Foundation.h>
@interface BirdSighting : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *location;
@property (nonatomic, copy) NSDate *date;
-(id) initWithName: (NSString *) name location:(NSString *) location date:(NSDate *) date;
@end
BirdSighting.m
#import "BirdSighting.h"
@implementation BirdSighting
-(id) initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date
{
self = [super init];
if(self) {
_name = name;
_location = location;
_date = date;
return self;
}
return nil;
}
@end
BirdSightingDataController.h
#import <Foundation/Foundation.h>
@class BirdSighting;
@interface BirdSightingDataController : NSObject
@property (nonatomic, copy) NSMutableArray *masterBirdSightingList;
- (NSUInteger) countOfList;
- (BirdSighting *) objectInListAtIndex: (NSUInteger) theIndex;
- (void) addBirdSightingWithSighting: (BirdSighting *) sighting;
@end
BirdSightingDataController.m
#import "BirdSightingDataController.h"
@implementation BirdSightingDataController
- (id) init {
if(self = [super init]) {
NSMutableArray *sightingList = [[NSMutableArray alloc] init];
self.masterBirdSightingList = sightingList;
return self;
}
return nil;
}
-(NSUInteger) countOfList
{
return [self.masterBirdSightingList count];
}
- (BirdSighting *) objectInListAtIndex: (NSUInteger) theIndex
{
return [self.masterBirdSightingList objectAtIndex:theIndex];
}
- (void) addBirdSightingWithSighting: (BirdSighting *) sighting
{
[self.masterBirdSightingList addObject:sighting];
}
@end
这就是我尝试将 BirdSighting 实例添加到可变数组的地方:
#import "BirdsMasterViewController.h"
#import "BirdsDetailViewController.h"
#import "BirdSightingDataController.h"
#import "BirdSighting.h"
@implementation BirdsMasterViewController
- (void)awakeFromNib
{
[super awakeFromNib];
BirdSightingDataController *dataController = [[BirdSightingDataController alloc] init];
NSDate *date = [NSDate date];
BirdSighting *sighting = [[[BirdSighting alloc] init] initWithName:@"Ebabil" location:@"Ankara" date: date];
[dataController addBirdSightingWithSighting: sighting];
NSLog(@"dataController: %@", dataController.masterBirdSightingList);
self.dataController = dataController;
}
..........
@end
它在 BirdSightingDataController addBirdSightingWithSighting 方法中抛出 NSInvalidArgumentException ...
我究竟做错了什么?
这是完整的调试输出: 2012-11-26 01:22:38.495 BirdWatching[4597:c07] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x71899d0 2012-11-26 01:22:38.496 BirdWatching[4597: c07] *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSArrayI addObject:]:无法识别的选择器发送到实例 0x71899d0”