请建议我使用连接方法进行 xml 解析的好链接。
为什么需要连接方法?
在这里我遇到了扩展类的教程?
我不明白为什么需要扩展它?给我一些用连接进行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