(4/18)重學Standford_iOS7開發_架構和帶屬性字串_課程筆記,iphone4升級ios7

來源:互聯網
上載者:User

(4/18)重學Standford_iOS7開發_架構和帶屬性字串_課程筆記,iphone4升級ios7

第四課(乾貨課):

  (最近要複習考試,有點略跟不上節奏,這節課的內容還是比較重要的,仔細理解掌握對今後的編程會有很大影響)

  本節課主要涉及到Foundation和UIKit架構,基本都是概念與API知識,作者主要做一歸納整理。

  0、其他

    a.對象初始化

      ①通過alloc init(例如[[NSString alloc] initWithFormat:@"%d",2])

      ②通過類方法(例如[NSString StringWithFormat:@"%d",2])

      ③通過其他執行個體對象的方法(例如stringByAppendingString:)

    b.nil

      可以給nil發送訊息,但只會得到nil

      對於返回為struct類型的方法會返回未定義的類型

    c.動態綁定

      對象在執行期間(runtime)才會判斷所引用對象的實際類型.

      id(實質上為所有對象指標的類型如NSString *),這裡討論動態綁定主要為了明確哪些情況會出現編譯警告與運行崩潰,方便後面討論統一概念。

      課程中的原例子:

1 @interface Vehicle2 - (void)move;3 @end4 @interface Ship : Vehicle5 - (void)shoot;6 @end

      情況①:屬於正常使用方式,不會出現編譯警告與崩潰。

 1 Ship *s = [[Ship alloc] init]; 2 [s shoot]; 3 [s move]; 

      情況②:父類調用子類特有方法,編譯時間會有警告,運行時正常運行。

 1 Vehicle *v = s; 2 [v shoot]; 

      情況③:任意id類型調用子類方法,無編譯警告(因為類型為id),運行時若obj不為ship類,則會崩潰。若調用不存在的方法,則會出現編譯警告(儘管類型為obj)

 1 id obj = ...; 2 [obj shoot]; 3 [obj someMethodNameThatNoObjectAnywhereRespondsTo]; 

       請況④:其他類型調用子類方法,會出現編譯警告,若進行類型轉換則沒有編譯警告,但仍會崩潰。

1 NSString *hello = @”hello”;2 [hello shoot];3 Ship *helloShip = (Ship *)hello;4 [helloShip shoot];5 [(id)hello shoot];

     動態綁定的問題可能會引發嚴重的錯誤(如毫無節制的類型轉換等)

     解決動態綁定問題的思路:內省機制,協議

     內省:NSObject基類提供了一系列的方法如isKindOfClass:(是否為這個類或其子類的執行個體),isMemberOfClass:(是否為這個類的執行個體),respondsToSelector:(對象是否響應某方法)來在運行時檢測對象的類型。

     檢測方法的變數為選取器selector(SEL),使用方法如下:

1 if ([obj respondsToSelector:@selector(shoot)]) {2     [obj shoot];3 } else if ([obj respondsToSelector:@selector(shootAt:)]) {4     [obj shootAt:target];5 }6 7 SEL shootSelector = @selector(shoot);8 SEL shootAtSelector = @selector(shootAt:);9 SEL moveToSelector = @selector(moveTo:withPenColor:);
1 [obj performSelector:shootSelector];2 [obj performSelector:shootAtSelector withObject:coordinate];3 4 [array makeObjectsPerformSelector:shootSelector]; // 用於數組,批量對數組中的對象發送訊息5 [array makeObjectsPerformSelector:shootAtSelector withObject:target]; // target is an id6 7 [button addTarget:self action:@selector(digitPressed:) ...];//MVC中的target-action

 

   1、Foundation

    a.NSObject

      所有類型的基類,提供了一系列通用的方法。
      - (NSString *)description描述對象內容(格式化輸出%@),一般在子類中自實現。

      - (id)copy; // 嘗試複製為不可變對象
      - (id)mutableCopy; // 嘗試複製為可變對象

    b.NSArray

- (NSUInteger)count;- (id)objectAtIndex:(NSUInteger)index; //返回下標為index的數組元素- (id)lastObject; // 返回數組末尾元素- (id)firstObject; // 返回數組頭元素- (NSArray *)sortedArrayUsingSelector:(SEL)aSelector;//使用自訂方法對數組排序- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)selectorArgument;- (NSString *)componentsJoinedByString:(NSString *)separator;//將數組轉化為字串並用separator分隔

     c.NSMutableArray

1 + (id)arrayWithCapacity:(NSUInteger)numItems; // numItems is a performance hint only 2 + (id)array; // [NSMutableArray array] is just like [[NSMutableArray alloc] init]3 4 - (void)addObject:(id)object; // 在尾部加入元素5 - (void)insertObject:(id)object atIndex:(NSUInteger)index;//在下標index處插入元素6 - (void)removeObjectAtIndex:(NSUInteger)index;//移除index處元素

     數組的遍曆:

 1 NSArray *myArray = ...; 2 for (NSString *string in myArray) 3  {  4     // no way for compiler to know what myArray contains 5     double value = [string doubleValue]; // crash here if string is not an NSString  6 } 7  8 NSArray *myArray = ...; for (id obj in myArray) 9  {10     // do something with obj, but make sure you don’t send it a message it does not respond to 11     if ([obj isKindOfClass:[NSString class]]) 12     {13         // send NSString messages to obj with no worries14      }15 }    

     d.NSNumber

      對常用基本類型的封裝

1 NSNumber *n = [NSNumber numberWithInt:36];2 float f = [n floatValue];3 4 //便利初始化方式5 NSNumber *three = @3;6 NSNumber *underline = @(NSUnderlineStyleSingle); // enum7 NSNumber *match = @([card match:@[otherCard]]); 

     e.其他簡單類型

      NSValue、NSData、NSDate(NSCalendar,NSDataFormatter,NSDateComponents)、NSSet(NSMutableSet)、NSOrderedSet(NSMutableOrderedSet)

     f.NSDictionary

//初始化方式@{ key1 : value1, key2 : value2, key3 : value3 }//查表方式UIColor *colorObject = colors[colorString]; //常用方法- (NSUInteger)count;- (id)objectForKey:(id)key;

    g.NSMutableDictionary

1 //常用方法2 - (void)setObject:(id)anObject forKey:(id)key;//添加索引值3 - (void)removeObjectForKey:(id)key;//移除索引值4 - (void)removeAllObjects;5 - (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;//合并字典
1 //遍曆方式2 NSDictionary *myDictionary = ...;3    for (id key in myDictionary)4  {5     // do something with key here6     id value = [myDictionary objectForKey:key];7     // do something with value here 8 }

    h.屬性列表

    屬性列表是一種儲存資料的方式,定義為集合的集合,可以為NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData。

    可以對上述對象直接發送- (void)writeToFile:(NSString *)path atomically:(BOOL)atom;訊息儲存為屬性列表檔案

    i.NSUserDefaults

    輕量級的本機資料儲存

[[NSUserDefaults standardUserDefaults] setArray:rvArray forKey:@“RecentlyViewed”];//常用方法- (void)setDouble:(double)aDouble forKey:(NSString *)key;- (NSInteger)integerForKey:(NSString *)key; // NSInteger is a typedef to 32 or 64 bit int - (void)setObject:(id)obj forKey:(NSString *)key; // obj must be a Property List- (NSArray *)arrayForKey:(NSString *)key; // will return nil if value for key is not NSArray//儲存完畢後必須進行同步[[NSUserDefaults standardUserDefaults] synchronize];

    j.NSRange

1 typedef struct {2     NSUInteger location;3     NSUInteger length;4 } NSRange;5 6 //建立7 NSMakeRange(NSUInteger location,NSUInteger length);

  2、UIKit

    a.UIColor

//系統內建顏色[UIColor blackColor];[UIColor blueColor];[UIColor greenColor];...//RGB顏色+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;//alpha為透明度//HSB顏色+ (UIColor *)colorWithHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha;

    b.UIFont

//系統字型UIKIT_EXTERN NSString *const UIFontTextStyleHeadline NS_AVAILABLE_IOS(7_0);UIKIT_EXTERN NSString *const UIFontTextStyleBody NS_AVAILABLE_IOS(7_0);UIKIT_EXTERN NSString *const UIFontTextStyleSubheadline NS_AVAILABLE_IOS(7_0);UIKIT_EXTERN NSString *const UIFontTextStyleFootnote NS_AVAILABLE_IOS(7_0);UIKIT_EXTERN NSString *const UIFontTextStyleCaption1 NS_AVAILABLE_IOS(7_0);UIKIT_EXTERN NSString *const UIFontTextStyleCaption2 NS_AVAILABLE_IOS(7_0);//建立字型UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];//常用方法+ (UIFont *)systemFontOfSize:(CGFloat)pointSize;+ (UIFont *)boldSystemFontOfSize:(CGFloat)pointSize;

    c.UIFontDescriptor

 1 //建立一個字型 2 + (UIFont *)fontWithDescriptor:(UIFontDescriptor *)descriptor size:(CGFloat)size; 3  4 //使用舉例 5 UIFont *bodyFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; 6 UIFontDescriptor *existingDescriptor = [bodyFont fontDescriptor]; 7 UIFontDescriptorSymbolicTraits traits = existingDescriptor.symbolicTraits; 8 traits |= UIFontDescriptorTraitBold; 9 UIFontDescriptor *newDescriptor = [existingDescriptor fontDescriptorWithSymbolicTraits:traits];10 UIFont *boldBodyFont = [UIFont fontWithFontDescriptor:newDescriptor size:0];

    d.Attributed Strings

      ①NSAttributeString

        帶屬性的字串(不是字串),可通過字典設定一系列字元屬性。

//擷取特定範圍的字元屬性- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)range;//擷取對應字串- (NSString *)string;

       ②NSMutableAttributeString

//常用的動態設定屬性的方法- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range;- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range;- (void)removeAttribute:(NSString *)attributeName range:(NSRange)range;//轉化為可變字串- (NSMutableString *)mutableString
//舉例UIColor *yellow = [UIColor yellowColor];UIColor *transparentYellow = [yellow colorWithAlphaComponent:0.3];//字串屬性字典 @{ NSFontAttributeName :      [UIFont preferredFontWithTextStyle:UIFontTextStyleHeadline]   NSForegroundColorAttributeName : [UIColor greenColor],   NSStrokeWidthAttributeName : @-5,   NSStrokeColorAttributeName : [UIColor redColor],   NSUnderlineStyleAttributeName : @(NSUnderlineStyleNone),   NSBackgroundColorAttributeName : transparentYellow }
1 //for UIButton2 - (void)setAttributedTitle:(NSAttributedString *)title forState:...;3 //for UILable4 @property (nonatomic, strong) NSAttributedString *attributedText;5 //for UITextView6 @property (nonatomic, readonly) NSTextStorage *textStorage;

   3、作業

    無

 

  其它:本節課主要是理論鋪墊,著重API的講解,都是很常用的對象,因此務必做到熟練使用,在今後的iOS開發中才不會出現基礎問題。希望大家可以多多查閱文檔,實際編程時重點理解動態綁定等概念。

 

課程視頻地址:網易公開課:http://open.163.com/movie/2014/1/B/P/M9H7S9F1H_M9H7VPRBP.html

       或者iTunes U搜尋standford課程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.