我是一個Objective-C中的新手,當我從其他類調用NSArray時遇到問題。我有一個類來處理XML提要的解析,另一個來管理UItableview的東西。這很奇怪,因爲當它同步完成(使用NSXMLParser方法)時,所有數據都顯示在表中,但是當我使用NSURLConnection使其異步時,它解析所有數據,但調用它時數組爲空。如果我調用NSLog,它會在解析數據時顯示包含newsStories數組的所有數據,但當我調用它時會以某種方式刪除它。當我從另一個類調用它時NSArray是空的(xcode)
在分析器類我有和的NSXMLParser的所有方法:
- (void)parseXMLFileAtUrl:(NSString *)URL {
data = [[NSMutableData alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
data = [[NSMutableData alloc]init];
}
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//Reset the data as this could be fired if a redirect or other response occurs
[data setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data
{
//Append the received data each time this is called
[data appendData:_data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Start the XML parser with the delegate pointing at the current object
_parser = [[NSXMLParser alloc] initWithData:data];
newsStories = [[NSMutableArray alloc] init];
[_parser setDelegate:self];
[_parser setShouldProcessNamespaces:NO];
[_parser setShouldReportNamespacePrefixes:NO];
[_parser setShouldResolveExternalEntities:NO];
[_parser parse];
}
這是我如何調用數組:
-(BOOL) loadData{
NSString *latestUrl = [[NSString alloc] initWithString:feed];
if ([latestArray count] == 0) {
news = [[news_parser alloc]init];
[news parseXMLFileAtUrl:latestUrl];
[self setArray:news.newsStories];--- here it says null for Array and for newsItems
}
[latestUrl release];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
array = [[NSMutableArray alloc]init];
_News.rowHeight =85;
[self loadData];
[self._News reloadData];
}
任何幫助,將不勝感激,謝謝你們! 此致敬禮。
嗨!我已完成connectionDidFinishLoading方法: - (void)connectionDidFinishLoading :(NSURLConnection *)connection { _parser = [[NSXMLParser alloc] initWithData:data]; newsItems = [[NSMutableArray alloc] init]; [_parser setDelegate:self]; [_parser setShouldProcessNamespaces:NO]; [_parser setShouldReportNamespacePrefixes:NO]; [_parser setShouldResolveExternalEntities:NO]; [_parser parse]; } 數組保存數據,但是當我調用它來填充它的時候,如果它看起來非常基本,但是感謝您的幫助 – marsalal1014
請將來不要嘗試在代碼中粘貼代碼;我第一次看到你的帖子,我不需要在這裏重複。假設我不知道我在說什麼,請閱讀我的答案並實際嘗試我的建議。 – taxilian
嗨Taxilian,抱歉在那裏複製代碼,我以爲我沒有清楚地解釋我的自我。在我回答你的第一個問題之後,我做了一些研究,並且明白了你的意思,並且在幾次調試之後,我得到了它。感謝您的觀點和解釋。對不起,如果我的評論是不敬的。謝謝! – marsalal1014