《iOS5 programming cookbook》学习笔记1

来源:互联网 发布:美国人学中文 知乎 编辑:程序博客网 时间:2024/06/01 10:21

《iOS5 programming cookbook》学习笔记

看到这个同学的这篇文章,把它下了下来,粗粗一看觉得不错,正好进阶一下。我也写个笔记,每章一篇。

这位同学真好学啊,有新东西学了就这么开心。

这一系列的文章也会记录我的学习过程,这位同学去年11月份就接触这些了,与诸位同学之间的差距简直就是鸿沟啊。往事不可追,好好学习。

看完1.3了,学了一招,

Build for Profiling

If you want to test the performance of your app, use this setting. Profiling is theprocess by which you can find bottlenecks, memory leaks, and other quality-relatedissues not covered by unit testing.

Build for Archiving

When you are sure your app is production quality or simply want to distribute itto testers, use this setting. 

Build for Profiling原来可以直接就可以打开instruments,很方便,不过instruments还是不大会用啊。待续

1.6跳过啊,暂时跳过,1.6的内容,我看另外一篇文章即可,当时问题给解决了,就没有细看了。

到1.7了。

改给自己规范一下变量的命名规则了

pple conventions dictate certain rules for variable names. Determine the type of thevariable (for instance, integer, array, string, etc.) and then a descriptive name for it. Inan empty line of code, place the type of your variable first, following by its name.Variable names are advised to follow these rules:

  1. Follow the camelCase naming convention. If the variable name is one word, allletters must be lower-case. If the variable name is more than one word, the firstword must be entirely lower-case and the subsequent words must have their firstletter upper-case and the rest of their letters lower-case. For instance, if you wantto have a counter variable, you can simply name itcounter.If you want to call yourvariable "first counter", declare itfirstCounter.The variable name "my very longvariable name" would becomemyVeryLongVariableName.(Names of that length arequite common in iOS programs.)

  2. Variables should ideally have no underline in their names. For instance,my_variable_namecan and perhaps should be changed tomyVariableName.

        3. Variable names should contain only letters and numbers (no punctuations such ascomma and dash). This is a restriction in the Objective-C language. 

再记一点也无妨,啦啦

There are certain rules, as mentioned before, about naming your variables (for instance,the camelCase rule). However, other aspects of your variable naming convention de-pend entirely on your choice. In general, I advise that you always assume you areworking for a big organization (whether it is your own company or somebody else'scompany) and follow these rules:

  1. Give descriptive names to your variables. Avoid names such as "i" or "x." Thesenames will never make any sense to anybody else but yourself and chances are thatthey won't make sense to you either if you leave the project for some time and comeback to it after a few months. The compiler doesn't really care if the variable nameis 50 letters long. If that makes your variable name more descriptive and you cannotdo without it, then go for it.

  2. Avoid creating vague variable names. For instance, if you have a string variable andyou want to place the full name of a person in that variable, avoid giving it namessuch as "theString" or "theGuy" or "theGirl." These make no sense at all. It is bestto give a name such as "fullName" or "firstAndLastName" rather than somethingthat confuses everybody who looks at your source code, including yourself!

  3. Avoid giving names to your variables that are likely to lead to mistyping. For in-stance, it is much better to call your variable "fullName" rather than"__full______name." It is much better to avoid underlines in variables all together. 

基本上我能做到,有则改之,无则加勉。


1.8

if (<replaceable>condition</replaceable>){

/* Your code to get executed if the <replaceable>condition</replaceable> is met */} 

As long as the condition is a value other than zero/nil/NULL, the codeinside the if statement will run. 


We use the double-equal sign in a conditional because the result of adouble-equal is a boolean value, whereas the single-equal sign mightconfuse the compiler and usually returns the value/object on the leftside of the equal sign. It is best to avoid using single-equal signs in aconditional like an if statement. Instead, compare your values usingdouble-equal signs. 

虽然话是这么说,但是我经常看到,

    - (id)init { 

        // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init 

        if (self = [super init]) {

    

            creationDate = [[NSDate alloc] init];

            

            return self;

        

        }

    

        return nil;

    

    }

这段代码,搞得我很久以来都以为 self == [super init],打印错误。

1.12

 two categories: instanceorclass.Instance methods are methodsthat can be called on an instance of the class (that is, on each object you create basedon the class), whereas class methods get called on the class itself and do not require aninstance of the class to be created by the programmer.  



看到1.13了,已是深夜11.33,困死,睡先。

2012.9.28

1.13的最后还有方法的命名规范,贴一下

  1. Here is a concise extract of the things to look out for when constructing and workingwith methods:

    • Have your method names describe what the method does clearly, without usingtoo much jargon and abbreviations. A list of acceptable abbreviations is in theCoding Guidelines.

page66image14328
page66image14600

48 | Chapter 1: The Basics

  • Have each parameter name describe the parameter and its purpose. On a methodwith exactly three parameters, you can use the wordandto start the name of thelast parameter if the method is programmed to perform two separate actions. Inany other case, refrain from usingandto start a parameter name.

  • Start method names with a lowercase letter.

  • For delegate methods, start the method name with the name of the class that in-vokes that delegate method. 

1.14

  1. 1. Allocation

    2. Initialization 


  1. This method creates the internal structure of a new object and sets allinstance variables’ values to zero. After this step is done, theinitmethod takes care of

page67image19176
page67image19448

setting up the default values of variables and performing other tasks, such as instanti-ating other internal objects. 



MyObject *someObject = [MyObject alloc];
/* Do something with the object, call some methods, etc. */[someObject doSomething]; 

还可以这么玩,真没玩过。不禁感慨,有些事情,平时老这么干,可是为什么这么干呢,有没有想过,如果不这么干会怎么样,


同时问过我这个问题,呵呵

In an older version of the Objective-C runtime, for@propertyto work,we also had to define aninstance variable.An instance variable is a var-iable whose memory management is done by the programmer herself.Instance variables are alsonotexposed to classes outside the scope ofthe class that defines them (that is, they are not exposed to any classthat simply imports the class with the instance variable). Instance vari-ables are normally calledivarsby professional Objective-C developers.Ivars is pronounced like I-VAR with the VAR part pronounced likeWAR, with a V.

With the new runtime, we don't have to define ivars anymore. We sim-ply define the property and the LLVM compiler defines the ivar for us.If you are using the GCC compiler, which is rather unlikely, you will seebig differences from how the LLVM compiler treats ivars. For instance,in GCC 4.2, an ivar isnotaccessible to any subclass of a class, whereasif you are using LLVM Compiler, a subclass of a class can use its super-class's ivars. So make sure you are using Apple's latest compiler, whichis LLVM. 


看到1.16了

一直不知道是什么意思,先睡了,困。10、57

strong

An object of this type is automatically retained at run-time and will be valid untilthe end of its scope, where it will automatically be released. For those familiar withObjective-C's traditional way of memory management, this keyword is similar tothe retainkeyword.

weak

This is zeroing weak referencing. If a variable is defined with this keyword, whenthe object to which this variable points gets deallocated, this value will get set tonil. For instance, if you have a strong string property and a weak string propertyand set the weak property's value to the strong property's value, when the strongproperty gets deallocated, the weak property's value will get set tonil.

unsafe_unretained

This is simply pointing one variable to another. This will not retain the object intothe new variable, it will simply assign the objct to the variable. 


不懂的东西怎么还是不懂,weak和unsafe_unretained 有什么区别,但是长进的是,知道了。

Any objectunder ARC is managed with one of these storage attributes. 

似乎arc底下就是用这个三个属性的??

 

1.16看的不是很明白,可能是因为之前没有吧。

When our app starts for the first time, we will initialize the strongstring1property and will assignstring1to string2.We will then set the value of thestring1property tonil.Then we will wait. This is absolutely crucial. If immediately after setting the value ofstring1tonil,you print out the value of string2, chances are that you will get incorrect results instead ofnil.So you need to make sure that your app's runloop has gotten rid of all invalidated objects. In order to achieve this, we will print the value ofstrong2when our app gets sent to the background. (This is caused by the user bringing another app to the foreground.) Once we're running in the background, we know that the runloop has already gotten rid of invalidated objects in the memory and the results that we will get will be accurate:

这段话里面提到了一个runloop的概念,我可以深究一下。这个我之前不知道,应该不在arc的模式下,也是有这个概念的。

1.17刚开始就看不懂这个单词Typecasting

问了一下身边的英语大神,也是不得其解。看着看着,

Typecasting is the process of pointing one value of type A to another value of type B.原来文中自己有解释。

Remember that Automatic Reference Counting does not work for Core Foundation objects, so we need to assist the compiler.

__bridge

Simply typecasts the object on the right side of the equation to the left side. This will not modify the retain count on any of the objects; neither the one on the left nor the one on the right side of the equation.

__bridge_transfer

This typecast will assign the object on the right side to the object on the left and will release the object on the right side. So if you have a Core Foundation string, like the one we saw before, that you have just created and want to place it inside a local variable of type NSString (local variables are by default strong, see Rec- ipe 1.16),then you should use this typecasting option because then you wouldn't have to release the Core Foundation string after the assignment. We will see an exmaple of this soon.

__bridge_retained
This is similar to the__bridge_transfertypecast, but will retain the object on the right side of the equation as well.

看到这里了,下火车了,未完待续。

当日,深夜10.56丈母娘家继续,

这123在了解了上面的规则之后,都能看明白,

1. We allocated a Core Foundation string and placed it inside thecoreFoundation Stringlocal variable. Since this is a Core Foundation object, ARC will not apply storage attributes to it, so we need to handle its memory manually. Its retain count is 1, as with any newly created variable.

2. Then we typecast this Core Foundation string to a generic object of typeid.Note that we didn't retain or release this object, so the retain count on bothunknownOb jectTypeandcoreFoundationStringstays 1. We simply typecasted it to an object of typeid.

3. Now we are retaining the generic object of type id and placing the resulting object into another Core Foundation string. At this time, the retain count on thecore FoundationString, unknownObjectType,andanotherStringvariables is 2 and all three of these variables point to the same location in the memory.

1中的apply storage attributes to it,额,是不是上面我拉了点东西啊。导致我后面就不理解了。

4的(because of the strong NSString variable, shooting the retain count from 1 to 2 again

这句话应该就是1中的那个apply storage attributes to it意思吧,反正456就看不懂了,

4. What we are doing after that is to assign the value inside coreFoundationString to a strong local NSStringusing the__bridge_transfertypecasting option. This will make sure that thecoreFoundationStringobject will get released after this assign- ment (the retain count will go from 2 to 1) and it will again be retained (because of the strongNSStringvariable, shooting the retain count from 1 to 2 again) So nowcoreFoundationString, unknownObjectType, anotherStringand theobjCStringvar- iables all point to the same string with the retain count of 2.

5. Next stop, we are setting our strong local variable objCString to nil. This will release this variable and our string's retain count will go back to 1. All these local variables are still valid and you can read from them because the retain count of the string that all of them point to is still 1.

6. Then we are explicitly releasing the value in the anotherString variable. This will set the release count of our object from 1 to 0 and our string object will get deal- located. At this point, you should not use any of these local variables because they are pointing to a deallocated object—except for the objCString strong local vari- able, whose value was set tonilby us.

回去看了一下上面那一章,__strong NSString *yourString = @"Your String";,是不是省略了这个__strong,这个意思。日后再补补吧。

1.18 Delegating Tasks with Protocols

不看了,影响夫人休息,睡了。2012/10/2  11.07

2012/10/3 7.26,起床洗漱完毕,等早饭中,继续,这部分内容,本来就知道了,所以看起来应该会比较简单。

这里有一段话,个人认为写的挺好的,写的很透彻。

Cocoa Touch has given protocols a really nice meaning in Objective-C. In Cocoa Touch, protocols are the perfect means for definingdelegate objects.A delegate object is an object that another object consults when something happens in that object. For instance, your repair man is your delegate if something happens to your car. If some- thing happens to your car, you go to yoru repair man and ask him to fix the car for you (although some prefer to repair the car themselves, in which case, they are their own delegate for their car). So in Cocoa Touch, many classes expect a delegate object and make sure that whatever object is assigned as their delegate conform to a certain pro- tocol.

 

看到1.19

先介绍了两个概念

Base SDK

The SDK that you use to compile your application. This can be the latest and the greatest SDK with access to all the new APIs available in iOS SDK.

Deployment SDK/Target

This is the SDK that will be used when you compile your app to run on devices.

这个是方法1:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"Item 1",

@"Item 4", @"Item 2", @"Item 5", @"Item 3", nil];

NSLog(@"Array = %@", array);
if ([NSArray instancesRespondToSelector:@selector(sortUsingComparator:)]){

/* Use the sortUsingComparator: instance method of the array to sort it */

}
else if ([NSArray instancesRespondToSelector:

@selector(sortUsingFunction:context:)]){

/* Use the sortUsingFunction:context: instance method of the array to sort */

}
else {

/* Do something else */ }

方法2:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:

@"Item 1", @"Item 4", @"Item 2", @"Item 5", @"Item 3", nil];

NSLog(@"Array = %@", array);
if ([array respondsToSelector:@selector(sortUsingComparator:)]){

/* Use the sortUsingComparator: instance method of the array to sort it */

}
else if ([array respondsToSelector:@selector(sortUsingFunction:context:)]){

/* Use the sortUsingFunction:context: instance method of the array to sort */

}
else {

/* Do something else */ }

1.20

Use the NSClassFromString function. Pass the name of your class to this method as a string. If the return value of this function isnil,that class isnotavailable on the device that runs your app; otherwise, that class is available on the device and you can go ahead and use it as you wish. Here is an example:

if (NSClassFromString(@"NSJSONSerialization") != nil){

/* You can use this class */
[NSJSONSerialization JSONObjectWithData:... /* Put data here */

options:... /* Put options here */ error:...]; /* Handle errors here */

} else {
/* That class is not available */

}

string 之类的就直接跳过了。

直接跳到1.26 bundle,貌似以前看过。

从亲戚家玩了一天回来,丈母娘在工作和老婆大人都在学习,我也把电脑拿出来看书了。

看完1.26,我继续1.27.

1.28,这一小结草草过了,呵呵,打算有时间试一下。

看到1.29消息中心。最后这个有点懒得看了,也晚了,都9.44了。

第二章是讲控件的,我怎么也想跳过去了啊。

现在试一下,bundle。


先放着,有种看字典的感觉,以后需要的时候再当字典查吧,打算转移,看iPhone Developer's Cookbook,先挂着

看了这篇文章,觉得这本书是不错啊,呵呵,我是不是得有空继续我的进度啊,哈哈

http://www.devdiv.com/iOS_iPhone-iOS_5_Programming_Cookbook中文翻译各章节汇总--结束更新9月10日-thread-122853-1-1.html

 

原创粉丝点击