(4/18) re-learn Standford_iOS7 development _ framework and course notes with attribute strings _, upgrade iOS 7 for iPhone 4

Source: Internet
Author: User
Tags traits

(4/18) re-learn Standford_iOS7 development _ framework and course notes with attribute strings _, upgrade iOS 7 for iPhone 4

Lesson 4 (dry goods course ):

(I have to review the exam recently, but it cannot keep up with the pace. The content of this lesson is still very important. Understanding it carefully will have a great impact on future programming)

This course mainly involves the Foundation and UIKit framework, which are basic concepts and API knowledge. The author mainly makes a summary.

0. Others

A. object initialization

① Use alloc init (for example, [[NSString alloc] initWithFormat: @ "% d", 2])

② Use class methods (for example, [NSString StringWithFormat: @ "% d", 2])

③ Use methods of other instance objects (such as stringByAppendingString :)

B. nil

Messages can be sent to nil, but only nil is returned.

An undefined type is returned for methods that return the struct type.

C. dynamic binding

The actual type of the referenced object is determined only when the object is executed (runtime.

Id (essentially the type of all object pointers, such as NSString *). The dynamic binding is discussed here to identify the situations where compilation warnings and run crashes will occur, so that the unified concept can be discussed later.

Original example in the course:

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

Scenario 1: normal use, no compilation warning or crash.

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

Scenario 2: the parent class calls the special method of the subclass. A warning is reported during compilation and runs normally during runtime.

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

Case ③: The subclass method is called for any id type without any compilation warning (because the type is id). If obj is not a ship class during runtime, it will crash. If you call a method that does not exist, a compilation warning will appear (although the type is obj)

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

Condition ④: If the subclass method is called for another type, a compilation warning is displayed. If the type conversion is performed, no compilation warning is generated, but the system will crash.

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

Dynamic binding may cause serious errors (such as uncontrolled type conversion)

Thoughts on solving the dynamic binding problem: Introspection mechanism and Protocol

Introspection: The NSObject base class provides a series of methods such as isKindOfClass: (whether it is an instance of this class or its subclass), isMemberOfClass: (whether it is an instance of this class ), respondsToSelector: (whether the object responds to a method) to detect the object type at runtime.

The variable of the detection method is selector (SEL). The usage is as follows:

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 primary mselector: shootSelector]; 2 [obj primary mselector: shootAtSelector withObject: coordinate]; 3 4 [array makeObjectsPerformSelector: shootSelector]; // used for arrays, send messages to objects in the array in batches 5 [array makeObjectsPerformSelector: shootAtSelector withObject: target]; // target is an id6 7 [button addTarget: self action: @ selector (digitPressed :)...]; // target-action in MVC


1. Foundation

A. NSObject

All types of base classes provide a series of common methods.
-(NSString *) description describes the object content (formatted output % @), which is generally self-implemented in the subclass.

-(Id) copy; // try to copy to an immutable object
-(Id) mutableCopy; // try to copy to a mutable object

B. NSArray

-(NSUInteger) count;-(id) objectAtIndex :( NSUInteger) index; // return the array element-(id) lastObject whose subscript is index; // return the array End Element-(id) firstObject; // return the array Header element-(NSArray *) sortedArrayUsingSelector :( SEL) aSelector; // use a custom method to sort Arrays-(void) makeObjectsPerformSelector :( SEL) aSelector withObject :( id) selectorArgument;-(NSString *) componentsJoinedByString :( NSString *) separator; // convert the array into a string and separate it with a 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; // Add element 5-(void) to the end) insertObject :( id) object atIndex :( NSUInteger) index; // insert element 6-(void) removeObjectAtIndex (NSUInteger) index at the subscript index; // remove the element at the index

Array traversal:

 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

Encapsulation of common basic types

1 NSNumber * n = [NSNumber numberWithInt: 36]; 2 float f = [n floatValue]; 3 4 // convenient Initialization Method 5 NSNumber * three = @ 3; 6 NSNumber * underline = @ (NSUnderlineStyleSingle); // enum7 NSNumber * match = @ ([card match: @ [otherCard]);

E. Other simple types

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

F. NSDictionary

// Initialization method @ {key1: value1, key2: value2, key3: value3} // look-up method UIColor * colorObject = colors [colorString]; // common method-(NSUInteger) count;-(id) objectForKey :( id) key;

G. NSMutableDictionary

1 // common method 2-(void) setObject :( id) anObject forKey :( id) key; // Add key value 3-(void) removeObjectForKey :( id) key; // remove the key value 4-(void) removeAllObjects; 5-(void) addEntriesFromDictionary :( NSDictionary *) otherDictionary; // merge the dictionary
1 // Traversal method 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. attribute list

The attribute list is a data storage method. It is defined as a set, which can be NSArray, NSDictionary, NSNumber, NSString, NSDate, or NSData.

You can directly send the-(void) writeToFile :( NSString *) path atomically :( BOOL) atom to the above object. The message is saved as an attribute list file.

I. NSUserDefaults

Lightweight local data storage

[[NSUserDefaults standardUserDefaults] setArray: rvArray forKey: @ "RecentlyViewed"]; // common method-(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 // after saving, you must synchronize [NSUserDefaults standardUserDefaults] synchronize];

J. nsange

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

2. UIKit

A. UIColor

// System built-in color [UIColor blackColor]; [UIColor blueColor]; [UIColor greenColor];... // RGB color + (UIColor *) colorWithRed :( CGFloat) red green :( CGFloat) green blue :( CGFloat) blue alpha :( CGFloat) alpha; // alpha is opacity // HSB color + (UIColor *) colorWithHue :( CGFloat) hue saturation :( CGFloat) saturation brightness :( CGFloat) brightness alpha :( CGFloat) alpha;

B. UIFont

// System Font: UIKIT_EXTERN NSString * const limit (7_0); UIKIT_EXTERN NSString * const limit (7_0); UIKIT_EXTERN NSString * const limit NS_AVAILABLE_IOS (7_0 ); UIKIT_EXTERN NSString * const limit NS_AVAILABLE_IOS (7_0); UIKIT_EXTERN NSString * const limit (7_0); UIKIT_EXTERN NSString * const limit NS_AVAILABLE_IOS (7_0 ); // new font UIFont * font = [UIFont preferredFontForTextStyle: Regular]; // common method + (UIFont *) systemFontOfSize :( CGFloat) pointSize; + (UIFont *) boldSystemFontOfSize :( CGFloat) pointSize;

C. UIFontDescriptor

1 // create a font 2 + (UIFont *) fontWithDescriptor :( UIFontDescriptor *) descriptor size :( CGFloat) size; 3 4 // use example 5 UIFont * bodyFont = [UIFont preferredFontForTextStyle: UIFontTextStyleBody]; 6 UIFontDescriptor * existingDescriptor = [bodyFont fontDescriptor]; 7 UIFontDescriptorSymbolicTraits traits = existingDescriptor. symbolicTraits; 8 traits | = bytes; 9 UIFontDescriptor * newDescriptor = [existingDescriptor attributes: traits]; 10 UIFont * boldBodyFont = [UIFont attributes: newDescriptor size: 0];

D. Attributed Strings

① NSAttributeString

Character string with attributes (not a string). You can set a series of character attributes through dictionaries.

// Obtain the character attribute of a specific range-(NSDictionary *) attributesAtIndex :( NSUInteger) index Returns tiverange :( nsangepointer) range; // obtain the corresponding string-(NSString *) string;

② NSMutableAttributeString

// Common method for dynamically setting attributes-(void) addAttributes :( NSDictionary *) attributes range :( nsange) range;-(void) setAttributes :( NSDictionary *) attributes range :( nsange) range;-(void) removeAttribute :( NSString *) attributeName range :( nsange) range; // convert it to a variable string-(NSMutableString *) mutableString
// For example, UIColor * yellow = [UIColor yellowColor]; UIColor * transparentYellow = [yellow colorWithAlphaComponent: 0.3]; // string attribute dictionary @ {NSFontAttributeName: [UIFont identifier: identifier] identifier: [UIColor greenColor], NSStrokeWidthAttributeName: @-5, NSStrokeColorAttributeName: [UIColor redColor], identifier: @ (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. Homework



Others: This course mainly serves as a theoretical basis, and focuses on API explanations, which are very common objects. Therefore, you must be skillful in using them so that basic problems will not occur in iOS development in the future. I hope you can read more documents and understand dynamic binding and other concepts in actual programming.


Course video address: Netease Open Class: http://open.163.com/movie/2014/1/ B /P/M9H7S9F1H_M9H7VPRBP.html

Or use iTunes U to search for standford courses

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.