所以我有一个自定义TVShow对象,它有一些基本字段,如id,showName,airDate等,它们都是NSStrings或NSIntegers,我试图通过我从API获得的一些数据创建一堆这些对象在线。
所以我遍历我的NSArray的JSON数据并为每个响应创建一个TVShow对象:
TVShow *show = [[TVShow alloc] initWithData:[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]];
[self.showArray addObject:show];
但是,只创建了其中的7个,然后下面的任何代码都停止运行。我有一个NSLog(@"已添加");在我创建节目后打印,它只被调用6次。如果我在任何代码之后添加断点,它们永远不会被调用。我不知道发生了什么,但它必须与我如何设置我的TVShow对象有关?
目前看起来像:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface TVShow : NSObject
@property NSInteger showID;
@property NSString *showName;
@property NSString *airDate;
@property double rating;
@property NSString *imageUrl;
@property NSString *showSummary;
@property NSString *episodeSummary;
@property NSInteger season;
@property NSInteger episode;
- (id)initWithData:(NSDictionary *)data;
@end
和.m文件:
#import <UIKit/UIKit.h>
#import "TVShow.h"
@implementation TVShow
- (id)initWithData:(NSDictionary*)data {
self = [super init];
if(self) {
[self buildObjectFromData:data];
}
return self;
}
-(void)buildObjectFromData:(NSDictionary*)data {
NSDictionary *dict = [data objectForKey:@"_embedded"];
NSDictionary *dict2 = [dict objectForKey:@"nextepisode"];
NSDictionary *dict3 = [data objectForKey:@"image"];
NSString *airDate = [dict2 valueForKey:@"airstamp"];
NSInteger season = [[dict2 valueForKey:@"season"] integerValue];
NSInteger episode = [[dict2 valueForKey:@"episode"] integerValue];
NSString *episodeSummary = [dict2 valueForKey:@"summary"];
NSString *showName = [data valueForKey:@"name"];
NSString *showSummary = [data valueForKey:@"summary"];
NSString *imageUrl = [dict3 valueForKey:@"medium"];
NSInteger showID = [[data valueForKey:@"id"] integerValue];
self.airDate = airDate;
self.showName = showName;
self.season = season;
self.episode = episode;
self.showSummary = [self stringByStrippingHTML:showSummary];
self.episodeSummary = [self stringByStrippingHTML:episodeSummary];
self.imageUrl = imageUrl;
self.showID = showID;
}
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}
@end
如果我将对象创建为:[[TVShow alloc] init];一切正常,所以这个模型一定是错的是我所想的。我不确定下一步该尝试什么,但是在这里会非常感谢任何帮助。
答案 0 :(得分:0)
原来有些案例已经出现:
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}
进入无限循环。删除此代码段会修复冻结。