天天看點

《iOS5 programming cookbook》學習筆記8

記得上次寫過這篇,不知道跑哪裡去了,也不知道看到哪裡了,就随着記憶走吧。

那就在此補充一下,項目代碼裡面,用的是

 {

[req setHTTPBody: [postString  dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *httpConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];    

    [httpConnection start];

    [httpConnection release];

    httpConnection = nil;

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

//這裡用來擷取頭資訊

    //NSLog(@"擷取頭資訊");

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [self.recievedData appendBytes:[data bytes] length:[data length]];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    //NSLog(@"互動出錯");

    [[NSNotificationCenter defaultCenter] postNotificationName:notifycationString object:nil];

//    NSLog(@"error:%@",error);

//這裡表示互動出錯

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

}

但是書上,是用這種方式,看上去簡單很多,改天得空了,問問牛同僚。

NSString *urlAsString = @"http://pixolity.com/post.php";

urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];urlAsString = [urlAsString stringByAppendingString:@"&param2=Second"];

NSURL *url = [NSURL URLWithString:urlAsString];

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];[urlRequest setTimeoutInterval:30.0f];

[urlRequest setHTTPMethod:@"POST"];

NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection

sendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse *response,

NSData *data,NSError *error) {

if ([data length] >0 &&error == nil){

NSString *html = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];

NSLog(@"HTML = %@", html);}

else if ([data length] == 0 &&error == nil){

NSLog(@"Nothing was downloaded.");}

else if (error != nil){

NSLog(@"Error happened = %@", error);

}}]; 

8.4

8.5也看完了,看來了解http協定,對了解這些代碼很有幫助。

一口氣看到8.9 看例子代碼就行,挺簡單的

看這個還學會轉碼了

8.9 Serializing Arrays and Dictionaries into JSON    

 NSString * testdecode=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

發現公司項目裡面的代碼,都沒有這個條件判斷,

NSError *error = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrintederror:&error]; 

if ([jsonData length] > 0 &&error == nil){

NSLog(@"Successfully serialized the dictionary into data = %@", jsonData);

}

當然很多情況下,會報錯,這個時候,就需要對error進行判斷了。

8.10

個人覺得地下的代碼很有教育意義,簡直可以當模闆了,有各種異常處理,很好。

 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

  [dictionary setValue:@"Anthony"

                forKey:@"First Name"];

  [dictionary setValue:@"Robbins"

                forKey:@"Last Name"];

  [dictionary setValue:[NSNumber numberWithUnsignedInteger:51]

                forKey:@"Age"];

  NSArray *arrayOfAnthonysChildren = [[NSArray alloc] 

                                      initWithObjects:

                                      @"Anthony's Son 1", 

                                      @"Anthony's Daughter 1",

                                      @"Anthony's Son 2",

                                      @"Anthony's Son 3",

                                      @"Anthony's Daughter 2",

                                      nil];

  [dictionary setValue:arrayOfAnthonysChildren

                forKey:@"children"];

  NSError *error = nil;

  NSData *jsonData = [NSJSONSerialization 

                      dataWithJSONObject:dictionary

                      options:NSJSONWritingPrettyPrinted

                      error:&error];

  if ([jsonData length] > 0 &&

      error == nil){

    NSLog(@"Successfully serialized the dictionary into data.");

    error = nil;

    id jsonObject = [NSJSONSerialization 

                     JSONObjectWithData:jsonData

                     options:NSJSONReadingAllowFragments

                     error:&error];

    if (jsonObject != nil &&

        error == nil){

      NSLog(@"Successfully deserialized...");

      if ([jsonObject isKindOfClass:[NSDictionary class]]){

        NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;

        NSLog(@"Deserialized JSON Dictionary = %@", deserializedDictionary);

      }

      else if ([jsonObject isKindOfClass:[NSArray class]]){

        NSArray *deserializedArray = (NSArray *)jsonObject;

        NSLog(@"Deserialized JSON Array = %@", deserializedArray);

      }

      else {

      }

    }

    else if (error != nil){

      NSLog(@"An error happened while deserializing the JSON data.");

    }

  }

  else if ([jsonData length] == 0 &&

           error == nil){

    NSLog(@"No data was returned after serialization.");

  }

  else if (error != nil){

    NSLog(@"An error happened = %@", error);

  }

  8.12 正好,這個也可以和項目中的代碼做一個對比了

貌似還有點複雜啊,沒有json簡單,第一次直接看代碼,比較費勁了,囧

2了一陣子,回過味來了

//xml 的key

@property (nonatomic, strong) NSString *name;

//xml 的value

@property (nonatomic, strong) NSString *text;

//一堆屬性

@property (nonatomic, strong) NSDictionary *attributes;

//子項

@property (nonatomic, strong) NSMutableArray *subElements;

//父項

@property (nonatomic, weak) XMLElement *parent;

在斯坦福的視訊裡面,白胡子老爺爺也是這麼說的。應該是第一個例子裡面就說到這個了。這一點也是同僚們沒有做到的。

We want the subElements mutable array to be created only if it is nil when it is accessed,

hence, we place our allocation and initialization code for this property in its own getter 

method. If an XML element doesn't have sub elements and we never use that property,then there is no point allocating and initializing a mutable array for that element. Thistechnique is known as lazy allocation. 

嗯,不錯,lazy allocation。

這幾段代碼,費了我好久,哎,補充一下吧

這樣

<weichaotest shuxing="shuxingzhi"/> 

這樣

<firstName>Anthony</firstName>

還有這樣

 <person id="1">

  </person>

都算是一個

Element。

- (void)        parser:(NSXMLParser *)parser 

       didStartElement:(NSString *)elementName 

          namespaceURI:(NSString *)namespaceURI

         qualifiedName:(NSString *)qName

            attributes:(NSDictionary *)attributeDict

這個函數執行的時機,是在解析一個Element開始的時候,所謂開始的時候,沒啥好說的,知道什麼是element就可以了。

結束就有的說了

- (void)        parser:(NSXMLParser *)parser

         didEndElement:(NSString *)elementName

          namespaceURI:(NSString *)namespaceURI

         qualifiedName:(NSString *)qName{

  self.currentElementPointer = self.currentElementPointer.parent;

}

我的了解是碰到類似與這種字元/>或者</firstName>的時候執行,應該是從頭到尾,順序解析每個element的。沒人手把手教了解起來略微費勁。特别是狀态不好的時候。