obj-c学习笔记

当对象经过在dealloc方法处理时,该对象就已经处于已销毁状态,其它对该对象发任何消息都会报错

视图对象的创建。alloc。。可以发生在其它线程

「initWithNibName: bundle:」载入nib档案来初始化
「loadView」载入视图
「viewDidLoad」在载入视图至内存后会呼叫的方法
「viewDidUnload」在视图从内存中释放后(此时已经收到内存警告)会呼叫的方法(内存警告时会call)
「viewWillAppear」当收到视图在视窗将可见时的通知会呼叫的方法
「viewWillDisappear」當收到視圖在視窗將不可見時的通知會呼叫的方法
「viewDidAppear」当收到视图在视窗将不可见后的通知会呼叫的方法
「viewDidDisappear」当收到视图已去除、被覆盖或隐藏于视窗时的通知会呼叫的方法
「didReceiveMemoryWarning」收到系统传来的内存警告通知后会执行的方法
「shouldAutorotateToInterfaceOrientation」是否支持不同方向的旋转视图
「willAnimateRotationToInterfaceOrientation」在进行旋转视图前的会执行的方法(用于调整旋转视图之用)

viewDidUnload是在 [super didReceiveMemoryWarning];发送后调用的
一旦出现内存不足的情况,iOS平台会通知所有已经运行的app,不论是前台app还是后台挂起的app,都会收到 memory warning的notice;一旦app收到memory warning的notice,就应该回收占用内存较大的变量;
内存报警处理流程
1: app收到系统发过来的memory warning的notice;
2: app释放占用较大的内存;
3: 系统回收此app所创建的autorelease的对象;
4: app返回到已经打开的页面时,系统重新调用viewdidload方法,view重新加载页面数据;重新显示;
内存警告和 viewDidUnload 以controller为单位,向所有controller发送(先后顺序为导航controller的出栈顺序)。但前台controller 不会收到viewDidUnload, 导航controller及rootViewController及游离于导航栈以外的controller不是后台controller,不会收到viewDidUnload
The view controller calls its  viewDidUnload  method to inform subclasses that the self.view were removed. A subclass typically uses this method to release any strong references it has to self.view.
注:
1、继承有冒号,协议遵从无冒号。
2、只能单继承,可以遵从多个协议,放到<>中以逗号隔开。
3、Cocoa  使用 NSArray、NSDictionary、NSSet,不能存储基本数据类型(可以封装成NSNumber对象)、enum、struct(可以封装成NSValue对象)、nil(可以封装成NSNull对象),只能存 储 Objective-C 的对象。
4、字典(哈希表)NSDictionary 用于存储 key-value 的数据结构,与JAVA  中的 Map 类似。
哈希  NSSet 表示以 hash 方式计算存储位置的集合,与 JAVA  中的 HashSet 是一致的。在 NSSet中的每个对象都有一个唯一的hash 值,重复的对象将只能保留一个。
5、启动一个线程使用 start 方法,结束一个线程使用 exit 方法,但要注意如果你使用了 exit 方法,首先要将这个线程的引用计数器归 0 。 
6、objc中的BOOL跟C的BOOL不一样。C的BOOL是整型值,遵守0为FALSE,非0为TRUE,而objc中的BOOL遵守1为YES,0为NO,所以C中的TRUE不一定是YES。
7、xib中的file`s owner就是storyboard中的controller
-(BOOL) conformsToProtocol: (Protocol*) prot // 用于判断对象是否遵从某个 protocol。
8、subViews方法返回的对象不用release  

Directive             Meaning

@private              The instance variable is accessible only within the class that declares it.

@protected            The instance variable is accessible within the class that declares it and within classes
                       that inherit it. All instance variables without an explicit scope directive have
                       @protected scope.

@public               The instance variable is accessible everywhere.

@package              Using the modern runtime, an @package instance variable has @public scope inside
                       the executable image that implements the class, but acts like @private outside.

                       The @package scope for Objective-C instance variables is analogous to
                       private_externfor C variables and functions. Any code outside the class
                       implementation’s image that tries to use the instance variable gets a link error.

                       This scope is most useful for instance variables in framework classes, where @private
                       may be too restrictive but @protected or @public too permissive. 







-(BOOL) isMemberOfClass: (Class) clazz           用于判断对象是否是 clazz 类型的实例,但
                                                 不包含子类的实例。 

-(BOOL) isKindOfClass: (Class) clazz             用于判断对象是否是 clazz             类型的实例或
                                                 者 clazz 的子类的实例。 

                                                 用于判断类型类型或者对象是否能够回应某个
-(BOOL)      respondsToSelector:         (SEL)            类型类型
selector                                         方法,这个方法使用选择器表示。 

+(BOOL)      instancesRespondToSelector:         用于判断类型所产生的实例是否能够回应
(SEL) selector                                   某个方法,这个方法使用选择器表示。 

                                                 用于动态调用类型类型或者对象上的一个方
- (id) performSelector: (SEL) selector                          类型类型
                                                 法。  


Writability

These attributes specify whether or not a property has an associated set accessor. They are mutually exclusive.

readwrite

      Indicates that the property should be treated as read/write. This attribute is the default.

      Both a getter and setter method are required in the @implementation block. If you use the @synthesize
      directive in the implementation block, the getter and setter methods are synthesized.

readonly

      Indicates that the property is read-only.

      If you specify  readonly, only a getter method is required in the @implementation block. If you use
      the @synthesize directive in the implementation block, only the getter method is synthesized. Moreover,
      if you attempt to assign a value using the dot syntax, you get a compiler error.

Setter Semantics

These attributes specify the semantics of a set accessor. They are mutually exclusive.

strong

      Specifies that there is a strong (owning) relationship to the destination object.

weak

      Specifies that there is a weak (non-owning) relationship to the destination object.

      If the destination object is deallocated, the property value is automatically set to nil.

      (Weak properties are not supported on OS X v10.6 and iOS 4; use assign instead.)

copy

      Specifies that a copy of the object should be used for assignment.

      The previous value is sent a  releasemessage.

      The copy is made by invoking the copy method. This attribute is valid only for object types, which must
      implement the NSCopying   protocol.

assign

      Specifies that the setter uses simple assignment. This attribute is the default.

      You use this attribute for scalar types such as NSInteger and CGRect.

retain

      Specifies that  retainshould be invoked on the object upon assignment.

      The previous value is sent a  releasemessage.

      In OS X v10.6 and later, you can use the __attribute__ keyword to specify that a Core Foundation
      property should be treated like an Objective-C object for memory management: 

       @property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary;

Atomicity

You can use this attribute to specify that accessor methods are not atomic. (There is no keyword to denote
atomic.)

nonatomic

      Specifies that accessors are nonatomic. Bydefault,accessors are atomic.

Properties are atomic by default so that synthesized accessors provide robust access to properties in a
multithreaded environment—that is, the value returned from the getter or set via the setter is always fully
retrieved or set regardless of what other threads are executing concurrently. 

迭代器:NSArray是迭代的元素本身。。。NSDictionary是迭代的key
NSEnumerator *e = [mArray objectEnumerator]; 
//获取数组的迭代器,相当于JAVA 中的 Iterator,reserveObjectEnumerator 用于获取反转
之后的数组迭代器。与JAVA 一致的地方是你在使用迭代器时,不能对数组进行添加、删除
操作。 

id obj; 
while(obj=[e nextObject])

     NSLog(@"%@",obj); 


//for-each 快速枚举为 Objective-C 2.0 的新特性,Windows 上的 GNUStep 并不支持。
for(NSString *ms in mArray)

     NSLog(@"%@",ms); 




常用的日期格式化字符串如下所示: 

%Y                                            四位数的年 

%y                                            两位数的年 

%B                                            月份的英文全写,如January 

%b                                            月份的英文简写,如Jan 

%m                                            两位数的月份 

%A                                            星期的英文全写,如 Friday 

%a                                            星期的英文简写,如 Fri 

%d                                            两位数的日期 

%H                                            24 小时制的两位数小时 

%I                                            12 小时制的两位数小时 

%p                                            显示 A.M 或者 P.M 

%M                                            两位数的分钟 

%S                                            两位数的秒数 

%F                                            三位数的毫秒 

%Z                                            显示时区的名字 

%z                                            显示时区与标准时区的偏移时间 HHMM  



书目:

iphone os programming guide
core animation programming guide
property list programming guide
archives and serializations programming for cocoa
predicate programming guide
user defaults programming topics for cocoa
memery usage performance guidelines
Threading Programming Guide


objc中dot style只用于accessor,所以虽然实例实际上是指针,但要访问它的属性只能用dot。
如self.value = 1; // 这样用dot而不是->


Cocoa中要記住的幾件內存管理相關的重要事情歸納為下面幾條:
1 通過分配或復制創建的對象保持計數為1
2 假設任何別的方法獲取的對象保持計數為1. 而且在自動釋放池中. 要想在當前執行范圍外使用該對象, 就必須保持它
3 向集合添加對象時它就被保持, 從集合移走對象時就被釋放. 釋放集合對象(如NSArray)會釋放該集合當中所有的對象
4 確保有多少個alloc, copy, mutableCopy或retain消息就有多少release或autorelease消息發送給該對象. 換句話說, 確保您代碼的平衡
5 在訪問方法設置屬性時先保持, 再釋放
6 在程序中用@"..."結構創建的NSString對象是有效常量. 向它們發送retain或者release消息沒有用
7 使用便利構造方法創建的對象(如NSString的stringWithFormat)可以被認為會自動釋放
8 在使用你自己的參數實例時, 需要實現-dealloc方法來釋放


1、The interface file tells users how the class is connected into the inheritance hierarchy and what other classes—inherited or simply referred to somewhere in the class—are needed.
所以除implemetation外,只有含继承关系及要生成实例和发送消息时才需要import interface


Class objects also inherit from the classes above them in the hierarchy. But because they don’t have instance variables (only instances do), they inherit only methods.


2、Using the modern runtime, an @package instance variable has @public scope inside the executable image that implements the class, but acts like @private outside


3、Instance variables marked @private are only available to subclasses by calling public accessor methods, if they exist.


4、class object 用initialize方法(runtime自动调用)初始化:The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message.
Instance 用init方法()初始化。


5、super is a term that substitutes for self only as the receiver in a message expression. super是从定义消息发送的方法的class的superclass寻找,而不是message express的receiver的superclass。


super is simply a flag to the compiler telling it where to begin searching for the method to perform; it’s used only as the receiver of a message. But self is a variable name that can be used in any number of ways, even assigned a new value.


6、Inside an instance method, self refers to the instance; but inside a class method, self refers to the class object. 


alloc和init、autorelease返回的是相等的id值 ?是的


7、Protocols free method declarations from dependency on the class hierarchy, so they can be used in ways that classes and categories cannot.


protocol的目的就是:list a group of methods but not associate them with any particular class or implementation.


Note that a class can conform to a protocol without formally adopting it, simply by implementing the methods declared in the protocol.


When used to declare a protocol, a category interface doesn’t have a corresponding implementation. 


8、objc在interface中声明的方法都为public的,除非用类别(在源文件中进行)进行声明(在interface头文件中不存在,所以编译器并不向调用者可视此方法故而没有调用权限,但是若类别声明在interface头文件中,则跟直接声明在原始interface类中无异)
或者不在原始类中声明方法,而是直接在主实现中实现方法,则是私有的。
即:objc的私有方法是靠文件结构和编译器来完成的,而不是语法意义上的:如果要类中的方法要 调用类别方法,那么类别的interface也必须向类的实现暴露(即import之),同理如果类别的interface向外部暴露了,那么私有属性也没了。


9、Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment


Whether or not you specify the name of the instance variable, the @synthesize directive can use an instance variable only from the current class, not a superclass.


属性的重定义(子类,类别,协议中,只能改变可读写性,其它atrribute必须保持):
用类扩展  (空类别,且扩展实现要放在接口主实现中,若是非空类别,则在类别实现中属性要dynamic然后实现setter)可以实现保持外部接口不变,只改变内部接口的权限,当然如果把类别的接口暴露给外部,那么外部接口权限也变了;
用子类    可以改变子类继承的外部接口的权限且不改变父类。但是在子类中要dynamic属性并实现setter。


10、子类会继承父类的类别中的方法(注意非空类别不能定义变量,所以@synthesize也不能用)


Unless its methods don’t access any instance variables of the class, the category must import the interface file for the class it extends。


Class extensions are like anonymous categories, except that the methods they declare must be implemented in the main @implementation block for the corresponding class.
Using the Clang/LLVM 2.0 compiler, you can also declare properties and instance variables in a class extension.


11、Because mutation of the object during iteration is forbidden, you can perform multiple enumerations concurrently.


12、Superclass * a = [[Class alloc] init];
那么虽然a的instance是子类的。。但是它只能执行Superclass中的方法,而且方法是按Superclass中的声明的,可是在执行时却是执行Class类中的overriding方法。


It discovers the return type of a method, and the data types of its parameters, from the selector. Therefore, except for messages sent to statically typed receivers, dynamic binding requires all implementations of identically named methods to have the same return type and the same parameter types. (Although identically named class methods and instance methods are represented by the same selector, they can have different parameter types and return types.)


statice type使得overriding方法可以与overred方法有不一样的return和parameter type,Statically typed receivers are an exception to this rule because the compiler can learn about the method implementation from the class type.


13、A class method and an instance method with the same name are assigned the same selector. However, because of their separate domains, there’s no confusion between the two. 


14、A @finally{} block contains code that must be executed whether an exception is thrown or not.


The @catch{} blocks should be ordered from most‐specific to least‐specific(从具体到抽象).


15、The @synchronized() directive takes as its only argument any Objective‐C object, including self.. This object is known as a mutual exclusion semaphore or mutex.


The Objective-‐C synchronization feature supports recursive(递归) and reentrant(可重入) code.


the thread releases all the locks obtained with it; that is, every @synchronized() block is exited normally or through an exception.


16、内存管理
没用ARC:
如果没有重载dealloc,那么runtime会自动调用父类的dealloc,如果重载了,那么就要手动加入[super dealloc];同理没重载init会自动调用父类的init,重载了就要手动加入[super init];
用了ARC:
dealloc时,不用管super的情况,runtime会自动调用。但是init的情况同上。




只有当遇到alloc、copy、new、retain时才需要必须有对应的release或autorelease,其它内容分配方法不需要release对应。因为它们已经隐式地调用了autorelease方法。。此方法会把它们加入到当前的autorelease pool.
ARC下@autorelease pool内的所有内存会被排空,而MRC下@autorelease pool类似于NSAutoreleasePool类的api,因此只会向池中所有对象发送release消息,即引用计数减小。


--------------------------------------------------------------------------
Xcode 4.3.2 学习
--------------------------------------------------------------------------
加载过程:所以有Nib对象(含controller)被实例化并加载到内存,然后delegate(runtime管理的)之。。AppDelegate的作用很简单,就是处理UIApplication的回调,而不应该负责用户界面的处理。


irst Responder 表示当前响应用户触摸的屏幕上的对象。在应用程序生命周期内, First Responder 在用户与屏幕交互时变化。例如,假设有一个表单。当用户触摸表单中的某个文本域时,那个文本域将成为活动文本域,并担当 First Responder 的角色。


1、可以在controller实现文件中添加awakeFromNib函数,以实现界面加载完成后的初始化(以前的版本是在delegate实现文件中添加)


2、scrollView的contentSize就是能操作的平面大小,屏幕可以显示其中的任意部分。


3、Plist只支持foundation的基本类型,是NSUserDefaults的基础,分为XML(NSArray,NSDictionary)和二进制(NSData)两种。一次性读取整个文件到内存。


ios的所有app都是在sandbox中,互相不能访问:每个app都有一个虚拟主目录(uuid随机十六进制路径,对应sandbox):其中的应用程序包子目录(含签名)是只读的,其它子目录则用来存放:用户定义数据,caches,temp等。
而且在与itunes同步时,除caches和temp目录,其它的都要同步。


NSUserDefaults的值存放在首选项中,即sandbox的Preferences子目录中。采用key-value方式存储。
Setting Bundle通过NSUserDefaults进行存储并设置。


4、对象存档(archiving object):支持自定义对象,Nib即是用此方法。是一次读取整个文件到内存。


5、Core Data:对SQLite的封装
NSPredicate用来查询(可以指定约束条件)
NSEntityDescription用来插入对象
NSFetchedResultsController


6、webservices:XML或json
XML:
JSON:自动解析property list type (如:NSArray, NSNumber, NSDictionary, NSData, NSString等),其顶层为NSDictionary类型。
//json的负载为256B。


7、NSThread的回调method中应该有autoreleasepool
一般情况在子线程完成特定工作后可以通过如下向主线程交互
// Message back to the main thread。。。allDone是自定义方法
[self performSelectorOnMainThread:@selector(allDone:)
            withObject:[someData result] waitUntilDone:NO];


同win32的SendMessage不一样。。这里类似PostMessage..allDone是在主线程中完成


NSLock是mutex互斥锁
NSCondition是信号量锁(对应生产者/消费者模型)
NSOperation(通过subclass使用)
NSInvocationOperation

你可能感兴趣的:(properties,Class,interface,hierarchy,methods,variables)