0
請建議我使用連接方法進行xml解析的好鏈接。Xml使用NSURL委託方法解析
爲什麼需要連接方法?
這裏我遇到了擴展類的教程?
我不明白爲什麼需要延長它? 給我一些很好的例子,它做的XML與連接
#import "WebRequestAPI.h"
@interface NSObject(Extended)
-(void)setData:(NSString *)message items:(NSMutableArray *)items withtag:(int)tag;
@end
@interface ConnectionClass:NSObject{
NSMutableData *receivedData;
NSString *className;
NSString *rootName;
NSObject *m_delegate;
int tag;
}
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t;
@end
@implementation ConnectionClass
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t
{
m_delegate = delegate;
className = class;
rootName = root;
tag=t;
return self;
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
if (receivedData != nil) {
[receivedData appendData:data];
} else {
receivedData = [[NSMutableData alloc] initWithData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if([className length]==0) {
NSMutableArray *item = [[NSMutableArray alloc] initWithObjects:rootName,receivedData,nil];
[m_delegate setData:@"" items:item withtag:tag];
[item release];
}
else {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *strData = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *data = [strData dataUsingEncoding:NSUTF8StringEncoding];
XMLParser *xmlParser = [[XMLParser alloc] initWithData:data];
[xmlParser setClassName:className withRootName:rootName];
[xmlParser setDelegate:xmlParser];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser parse];
[m_delegate setData:xmlParser.message items:xmlParser.items withtag:tag];
[xmlParser release];
[strData release];
[pool release];
}
}
-(void)dealloc {
[receivedData release];
[super dealloc];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[m_delegate setData:@"Connection required." items:nil withtag:0];
}
@end
@implementation WebRequestAPI
-(id) init {
return self;
}
#pragma mark - demoAPI.
+ (void)demoApi:(NSObject *)delegate
{
int tag = 1;
NSString *demoStr = [NSString stringWithFormat:@"http://www.astrology.com/horoscopes/daily-horoscope.rss"];
demoStr = [demoStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // NSASCIIStringEncoding];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:demoStr]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
ConnectionClass *con = [[[ConnectionClass alloc]initWithClass:@"item" withRoot:@"" withDelegate:delegate withTag:tag]autorelease];
[[[NSURLConnection alloc]initWithRequest:theRequest delegate:con] autorelease];
}
@end
不,我想使用連接方法解析.. connectionDidFinishLoading但更簡單的方法,如果你可以請告訴我爲什麼擴展用在.m文件中? –
好的等待會給你u代碼示例 – Kasaname