2012年5月29日 星期二

Archive and Serialization

轉貼自

1. http://rintarou.dyndns.org/tag/objective-c/ 
2. developer.apple.com/library

3. 完整的例子可以參考http://blog.skp.idv.tw/kun/

Archive 與 Serialization 是為了將 Hierarchical data 與 byte stream 相互轉換(encode/decode)而設計的兩種機制。

Encode : Hierarchical data -> byte stream
Decode : byte stream -> Hierarchical data

Archives (Un-arhchive)
Archive 能處理包含 Object 本身,以及與其它 Object 之間的 Relationships (references),保存原來完整 Object graph 的資訊並轉換成 byte stream,例如:nib。
要支援 Archive 機制,就必須實作 NSCoding Protocol,在 Fundation 裡的一些 Value objects(NSString, NSArray, NSNumber 等)都有實作 NSCoding Protocol。

Mac OS X archives store an arbitrarily complex object graph. The archive preserves the identity of every object in the graph and all the relationships it has with all the other objects in the graph. When unarchived, the rebuilt object graph should, with few exceptions, be an exact copy of the original object graph.
Interface Builder uses archives (nib file) to store the objects and relationships that make up a user interface. A Cocoa application loads the nib archive to reconstruct a window, menu, or view that was designed in Interface Builder.
Your application can use an archive as the storage medium of your data model. Instead of designing (and maintaining) a special file format for your data, you can leverage Cocoa’s archiving infrastructure and store the objects directly into an archive. With minimal effort, you can implement Save and Open in your application.
To support archiving, an object must implement the NSCoding protocol, which consists of two methods. One method encodes the object’s important instance variables into the archive and the other decodes and restores the instance variables from the archive.
All of the Foundation value objects (NSString, NSArray, NSNumber, and so on) and most of the Application Kit user interface objects implement NSCoding and can be put into an archive. Each class’s reference document identifies whether they implement NSCoding.

Serializations
Mac OS X serializations store a simple hierarchy of value objects, such as dictionaries, arrays, strings, and binary data. The serialization only preserves the values of the objects and their position in the hierarchy. Multiple references to the same value object might result in multiple objects when deserialized. The mutability of the objects is not maintained.
Property lists are examples of serializations. Application attributes (the Info.plist file) and user preferences are stored as property lists.
Arbitrary objects cannot be serialized. Only instances of NSArray, NSDictionary, NSString, NSDate, NSNumber, and NSData (and some of their subclasses) can be serialized. The contents of array and dictionary objects must also contain only objects of these few classes.



Class hierarchy for coders




















2012年5月27日 星期日

Xcode 4.2改版記錄

轉貼自 http://patty0800.pixnet.net/blog/post/38681516-xcode-4.2%E6%94%B9%E7%89%88%E8%A8%98%E9%8C%84part1_main,-button-setfont,-cfurlref

main.m 繼承的改變:
原來:
int main(int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePoolalloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"SampleAppDelegate");
[pool release];
return retVal;
}
新版:
int main(int argc, char *argv[])
{
    @autoreleasepool {
        returnUIApplicationMain(argc, argv, nil, NSStringFromClass([AnimButtonFlipAppDelegateclass]));
    }
}

/***********************************************************************/

UIButton文字大小設定:
原來:
 [button setFont:[UIFont boldSystemFontOfSize:24.0f]];
新版:
 [button.titleLabel setFont: [UIFont boldSystemFontOfSize24.0f]];

/**********************************************************************/

Core Foundation URL Access Utilities Reference:
原來:
CFURLRef baseURL = (CFURLRef)[[NSURL alloc] initFileURLWithPath:sndpath];
新版:
CFURLRef baseURL = (__bridge CFURLRef)[[NSURL alloc] initFileURLWithPath:sndpath];

證券心理學之筆記

轉貼 http://rattlerlife.wordpress.com/2006/09/09/20060909-%E6%88%91%E8%AE%80%E3%80%8C%E7%A7%91%E6%96%AF%E6%89%98%E8%98%AD%E5%B0%BCkostolanys-%E8%AD%89%E5%88%B8%E5%BF%83%E7%90%86%E5%AD%B8%E3%80%8D-%E4%B9%8B%E7%AD%86%E8%A8%98/

1. 不論在世界上的那一個股票市場中,最不好的股票就是所謂的「概念股」,因為概念股的股價完全不隨趨勢走動,全球各地股市皆然。這個股票高低震盪,表現的只不過是十萬名歇斯底里的股票專家或所謂半調子行家的反應罷了,而這些人的想法往往說變就變。
2. 行情造就報導,而非報導造就行情。
3. 悲觀的根本源由其實在股票玩家的本身性格。
4. 「賭徒的謬見」(註1) – 如同杜斯妥也夫斯基(Fyodor Dostoevesky)在他的「賭徒」一書中提到 :「當球經落在紅色十次時,當然沒有人會再把錢押在紅色的部分。」投資人也完全以此為出發點,也就是當一段行情到達高點時,一定會再往下落的想法。
5. 一位成功的投資顧問性格必定有點高傲,甚至有鄙視其它投資大眾的傾向,這是為了令自己保持清醒,不受他人一時情緒反應而改變自己對股市走勢的看法。
6. 「群眾是無知的」隱藏在這句話背後的真正含義是群眾的力量。
7. 會影嚮股市行情的是投資大眾對重大事情的反應,而非重大事件本身。
8. 股市中、短期的漲跌90%受心理因素影響,而基本面則是左右股市長期表現的重要關鍵。
9. 決定股市走向的因素有兩點 :
(1) 資金流通量與新上市股票之間的關係。
(2) 樂觀或悲觀的心理因素 (也就是未來趨勢的評估)
T (Tendenz,趨勢) = G (Gold,資金) + P (Psychologie,心理)
10. 股票本益比的評估也純粹是一項心理變數。所謂「股價過高」或「股價過低」不過是比較之後的結果,並非像數學算式一般,可以算出標準答案。尤其是分析處於虧損狀態的公司時,這樣的行情分析法更顯得偏頗而不懂變通。
11. 「二乘二等於五減一」。在生活中,或操作股票時,沒有任何事是簡單的,所有事物皆依據事實而發生或存在。經驗告訴我們 : 「一定可以達成目標,只是中間的路程絕不是一條直線」。
12. 投資人決定投資策略時所依據的基本面利多,有可能和技術面相互抵銷,這就是投資人無法理解為何有時候明明是利多格局,但股市行情卻沒有作出相對反應的原因。所以不管如何,只要市場供應大量股票,行情便會相對下跌。
13. 股市行情雖然和經濟景氣互有關連,也遵循同一個法則,但兩者卻不是同時發生的。股市行情的起伏像狗一樣,向前走了一段之後,就會往後退幾步。在這個過程中,經濟成長也會隨之而來(註2)。兩個根本要素 :
(1) 資金及貸款情況
(2) 投資大眾的心理狀態
14. 對於股市大盤走勢(並非單一個股的走勢),想像力和資金要比基本面的分析更能發揮決定性的影響。雖說基本面的分析相當重要,但在交易量很大時,基本面的作用便無法完全發揮了。
15. 股價的波動從來未曾符合股票的真正價值,股價永遠過高或過低。如果股價可以隨時反應真正的價值,也就不會有上下波動的行情了。
16. 股市本身就是心理學。股市心理學就像是一場即席演講 : 在股票市場中,你永遠無法說準,會有什麼重大事件發生,投資大眾又會有什麼樣的反應,你只能猜測。
17. 一個出色的政治家,也可以擁有使人折服的領袖氣質。這一點非常重要,因為這樣的特質可以為經濟帶來充滿希望及信任的氣氛。
18. 電腦可以幫助我們隨時調閱過去所有資料或是某一年度的相關資料。但是電腦不能猜想未來的事,也不能代替投資人思考。
19. 片面的、短視的新聞分析,對股市是完全沒有意義的,因為投資人必須要有整體性的考量,眼光也要放遠。
20. 投機者需要經驗的累積,以便不斷憶起類似的情況。
21. 投機者不是一本百科全書,但他必須在關鍵時刻觀察出關聯性,並作出適宜的處理。他不必知道太多,但要通盤了解。簡單來說,他必須是個思想家。
註1 :
「賭徒謬誤」
賭徒和偶爾一賭的人不同。每個人在某些時刻都想贏一下─摒住氣息,只求命運恩賜這一次!這是普遍的渴望。在各種彩券遊戲中,只要有人嬴大錢,別人就開始夢想。這是此類賭博的目標;真正的報酬是夢想。
賭徒又是另一回事,他真正等著嬴錢。他投下的不是象徵性的小錢,而是能毀掉他的大數目。他有一套制度─在對策論中,這被稱為「賭徒謬誤」。在輪盤賭中,最常見的行為模式是所謂「戴倫伯特系統」,它正是以「賭徒謬誤」為基礎的。比方說,賭輪盤的時候他押紅的,失敗的時候再加倍。根據數學的機率法則,不管前面出現過多少次黑的,每次你押紅的,押中的機會仍是50:50。但是賭徒認為,黑色若連續出現幾次,下回紅色出現的機會就隨著輪子的連續性轉動而比例增加。即使這不合數理原則,賭徒心中卻愈來愈堅信紅的該來了─就算這次不來,下回一定會出現,於是下次更加肯定。這使他更相信自己會贏,他知道他會的,雖然事實上機會永遠一樣50:50。
我們可以說,常勝的賭徒就是靠運氣而自以為通曉了某些奧妙的人。(當然,必須考慮技術因素:有些人打牌或作弊的技術高。)如果運氣一直證明他的預感和先見之明─統計上一定會有幾個這麼幸運的人─他心裡就產生「不會輸」的感覺。事實上,他只是運氣好,但是他的運氣碰巧合乎他自覺幸運的信心,使他很容易相信自己的運氣是特殊的神恩,專門賜給天之驕子。
他相信自己註定要贏,他的勝利具有命中註定的意義。這種人渴望,有時也獲得的是「優異」的感覺。他要證明,命運偏愛他。否則富家老太太何必一夜一夜耗在俱樂部的賭臺上?她們要用錢來算命。古代紙牌、數字、骰子在算命、魔術和占星儀式所扮演的角色就指出了其中的關係。
但是賭徒不只是接受紙牌的預言,他也想向不溫厚的命運強討勝利。當他的數目不出現,他就越戰越勇,加倍下注,一直提高賭金。在他大膽或絕望的嘗試中,他會一舉贖回所有的損失。
由這種行為看來,賭徒是一個幻想自己必贏、卻表現出堅決失敗典型的人。
參考自 : http://hoi-yin.com/business/013.htm
註2 :
請想像一個人在街上溜狗。人很平穩地向前邁進 – 這就是經濟。而狗則有時向前狂奔,有時東跑西跳,有時跑回主人身旁,就這樣來來回回地跑來跳去。這隻狗的行經路線便是證券行情的起伏過程。

Copy and mutableCopy

refer to  Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009) 

int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray    *dataArray = [NSMutableArray arrayWithObjects:
@ ” one ” , @ ” two ” , @ ” three ” , @ ” four ” , nil];
NSMutableArray    *dataArray2;

// simple assignment
dataArray2 = dataArray;
[dataArray2 removeObjectAtIndex: 0]; //移除第一筆資料,看對dataArray的影響
NSLog (@ ” dataArray: “ );
for ( NSString *elem in dataArray )
NSLog (@ ” %@ ” , elem);
NSLog (@ ” dataArray2: “ );
for ( NSString *elem in dataArray2 )
NSLog (@ ” %@ ” , elem);

// try a Copy, then remove the first element from the copy
dataArray2 = [dataArray mutableCopy]; //產生兩個不同的記憶區塊
[dataArray2 removeObjectAtIndex: 0]; //移除第一筆資料,看對dataArray的影響
NSLog (@ ” dataArray: “ );
for ( NSString *elem in dataArray )
NSLog (@ ” %@ ” , elem); 
NSLog (@ ” dataArray2: “ );
for ( NSString *elem in dataArray2 )
NSLog (@ ” %@ ” , elem);

[dataArray2 release];  //只需對dataArray2做release動作就可以了
[pool drain];
return 0;
}

dataArray:
two
three
four
dataArray2:
two
three
four

dataArray:
two     //資料不受影響,因為dataArray區已經與dataArray2區不同了
three
four
dataArray2:
three
four

Another Example for  mutable strings

int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray    *dataArray = [NSMutableArray arrayWithObjects:
[NSMutableString stringWithString: @ ” one ” ], //裡面也是NSMutableString
[NSMutableString stringWithString: @ ” two ” ],
[NSMutableString stringWithString: @ ” three ” ],
nil
];
NSMutableArray    *dataArray2;
NSMutableString   *mStr;

NSLog (@ ” dataArray: “ );
for ( NSString *elem in dataArray )
NSLog (@ ” %@ ” , elem);

// make a copy, then change one of the strings
dataArray2 = [dataArray mutableCopy]; //  要產生兩個記憶區塊,但只針對dataArray裡的point參考區,有作複製的動作,對次一級的array資料區並沒有複製 
//因此dataArray及dataArray2雖有兩個不同point區的記憶區塊,但其兩邊的point只是指向相同的資料記憶區塊

mStr = [dataArray objectAtIndex: 0]; //針對array[0]將入"ONE"
[mStr appendString: @ ” ONE ” ];

NSLog (@ ” dataArray: “ );
for ( NSString *elem in dataArray )
NSLog (@ ” %@ ” , elem);

NSLog (@ ” dataArray2: “ );
for ( NSString *elem in dataArray2 )
NSLog (@ ” %@ ” , elem);

[dataArray2 release];
[pool drain];
return 0;
}

dataArray:
one
two
three

dataArray:
oneONE
two
three

dataArray2:
oneONE
two
three

以上所做的都只是shallow Copy,要將整個array內部含括所有Point指向的區塊的所有資料都備份,則需要Deep Copy 

Shallow and deep copies of an object 

 

Making a shallow copy
NSArray *shallowCopyArray=[someArray copyWithZone:nil];
 
NSDictionary *shallowCopyDict=[[NSDictionary alloc] initWithDictionary: someDictionary copyItems: NO];

Making a deep copy
NSArray *deepCopyArray=[[NSArray alloc] initWithArray: someArray copyItems: YES];
  

另一個真正的Deep Copy,使用壓縮解壓縮的方式, NSCoding protocol.

NSData *buffer;

buffer = [NSKeyedArchiver archivedDataWithRootObject: myArray1];
myArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];



 

Memory-Management 規則, 理由和啟動方法

refer to  Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)

1. Releasing an object can free up its memory, which can be a concern if you’re creat-
ing many objects during the execution of a program.A good rule is to release ob-
jects you’ve created or retained when you’re done with them.
自己創建的記憶體,自己釋放

2. Sending a  release message does not necessarily destroy an object.When an object’s
reference count is decremented to  0 , the object is destroyed.The system does this by
sending the dealloc message to the object to free its memory.
當reference count =0, dealloc 就會被叫出來執行

3. The autorelease pool provides for the automatic release of objects when the pool
itself is released.The system does this by sending a release message to each object
in the pool for each time it was autoreleased. Each object in the autorelease pool
whose reference count goes down to 0 is sent a dealloc message to destroy the ob-
ject. 

4. If you no longer need an object from within a method but need to return it, send it
an autorelease message to mark it for later release.The  autorelease message does
not affect the reference count of the object. So it enables the object to be used by
the message sender but still be freed up later when the autorelease pool is released.

autorelease適用在你想要在最後一次執行動作完再釋放記憶體時

5. When your application terminates, all the memory your objects take up is released,
regardless of whether they were in the autorelease pool.

6. When you develop more sophisticated applications (such as Cocoa applications), au-
torelease pools can be created and destroyed during execution of the program (for
Cocoa applications, that happens each time an event occurs). In such cases, if you
want to ensure that your object survives automatic deallocation when the autorelease pool itself is released, you need to explicitly retain it.All objects that have a reference count greater than the number of autorelease messages they have been sent
will survive the release of the pool.

7. If you directly create an object using an  alloc or copy method (or with an
allocWithZone: , copyWithZone: , or  mutableCopy method), you are responsible for
releasing it. For each time you  retain an object, you should  release or
autorelease that object.

8. You don’t have to worry about releasing objects that are returned by methods other
than those noted in the previous rule. It’s not your responsibility; those methods
should have autoreleased those objects.That’s why you needed to create the autore-
lease pool in your program in the first place. Methods such as  stringWithString :
automatically add newly created string objects to the pool by sending them
autorelease messages. If you don’t have a pool set up, you get a message that you
tried to autorelease an object without having a pool in place.
method所用到的記憶體由autorelease負責,所以一定要有autoreleased pool

三個理由要了解memory management
1.  First, even in an environment that supports garbage collection, it’s best to
know who owns your objects and to keep track of when you don’t need them anymore.
This will make you more meticulous about writing your code because you will under-
stand the relationships of your objects to each other and their lifespan in your program.
(自己了解整個記憶體的生命週期,對程式的開發有其好處)



2. The second reason, as has been previously noted, is that the iPhone runtime environ-
ment doesn’t support garbage collection, so you don’t have a choice when developing
programs for that platform. (iphone沒有garbage collection)

3. The third reason applies to you if you plan on writing library routines, plugins, or
shared code. Since that code might be loaded into a garbage-collected or non garbage-
collected process, it has to be written to work in both environments.
(如果要將程式碼轉移給別人,對記憶體管理要特別注意)

在Xcode中要自己啟動記憶體管理選項

When garbage collection is enabled, your program can still make its  retain ,
autorelease , release , and  dealloc method calls. 
The dealloc calls are ignored when garbage-collection is enabled.