1

我正在尝试编写自己的类来存储有关库的数据,然后将每个对象存储在 NSArray 中。

我的界面:

#import <Foundation/Foundation.h>

@interface LibraryInfo : NSObject
{

NSString* name;
NSString* address;
NSString* link;
NSString* coordinates;

}

- (NSString*) getName;
- (NSString*) getAddress;
- (NSString*) getLink;
- (NSString*) getCoordinates;

- (void) setName: (NSString*)input;
- (void) setAddress: (NSString*)input;
- (void) setLink: (NSString*)input;
- (void) setCoordinates: (NSString*)input;

@end

我的实现:

#import "LibraryInfo.h"

@implementation LibraryInfo

- (void) setName: (NSString*)input
{
name = input;
}

- (void) setAddress: (NSString*)input
{
address = input;
}

- (void) setLink: (NSString*)input
{
link = input;
}

- (void) setCoordinates: (NSString*)input
{
coordinates = input;
}

- (NSString*) getName {
return name;
}

- (NSString*) getAddress {
return address;
}

- (NSString*) getLink {
return link;
}

- (NSString*) getCoordinates {
return coordinates;
}

@end

我将每个对象写入并存储在 NSArray 中,如下所示:

LibraryInfo *library = [[LibraryInfo alloc] init];
[library setName:( ( name != nil && name.length > 0 ) ? name : @"No Name" )];
[library setAddress:( ( address != nil && address.length > 0 ) ? address : @"No Address" )];
[library setLink:( ( link != nil && link.length > 0 ) ? link : @"No Link" )];
[library setCoordinates:( ( coordinate != nil && coordinate.length > 0 ) ? coordinate : @"No Coordinates" )];
    
[libraries addObject: library];

其中“库”是一个 NSArray。

然后我尝试像这样读取值:

cell.textLabel.text = [[ libraries objectAtIndex:indexPath.row ] getName ];
cell.detailTextLabel.text = [[ libraries objectAtIndex:indexPath.row ] getAddress ];

我认为这可能与值的设置有关,或者它们没有正确存储或保留,但是
当应用程序“崩溃”并暂停时,我的“setName”方法出现以下错误和标记:

self    LibraryInfo *const  0x068a1760
input   NSString *  0x068a3550
name    NSString *  0x00000000

我该如何解决?我使用的是 Xcode 4.3,所以不需要发布/保留。

4

1 回答 1

4

您需要声明属性。Ivar 不会以您期望的方式存储您的数据

图书馆信息.h

@interface LibraryInfo : NSObject

@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSString* address;
@property (nonatomic, strong) NSString* link;
@property (nonatomic, strong) NSString* coordinates;

图书馆信息.m

@implementation LibraryInfo
@synthesize name;
@synthesize address;
@synthesize link;
@synthesize coordinates;

然后创建库会很简单

LibraryInfo *library = [[LibraryInfo alloc] init];
library.name = (name.length > 0 ? name : @"No Name");
library.address = (address.length > 0 ? address : @"No Address")
library.link = (link.length > 0 ? link : @"No Link")
library.coordinates = (coordinates.length > 0 ? coordinates : @"No Coordinates")

然后在您的 TableView 单元格中。

cell.textLabel.text = [libraries objectAtIndex:indexPath.row].name;
cell.detailTextLabel.text = [libraries objectAtIndex:indexPath.row].address;
于 2012-05-09T23:16:10.330 回答