回覆列表
  • 1 # 使用者5012245626884

    objectforkey是NSDictionary的方法,valueforkey是KVC的方法,兩者都是鍵值對應,區別是valueforkey只允許使用NSString型別,objectforkey可以是任意型別.objectForKey:isanNSDictionarymethod.AnNSDictionaryisacollectionclasssimilartoanNSArray,exceptinsteadofusingindexes,ituseskeystodifferentiatebetweenitems.Akeyisanarbitrarystringyouprovide.Notwoobjectscanhavethesamekey(justasnotwoobjectsinanNSArraycanhavethesameindex).valueForKey:isaKVCmethod.ItworkswithANYclass."valueForKey"allowsyoutoaccessaninstancevariableusingastring.Soforinstance,ifIhaveanAccountclasswithaninstancevariableaccountNumber,Icandothefollowing:NSNumber*anAccountNumber=[NSNumbernumberWithInt:12345];Account*newAccount=[[Accountalloc]init];[newAccountsetAccountNumber:anAccountNUmber];NSNumber*anotherAccountNumber=[newAccountaccountNumber];UsingKVC,Icanalsodoitlikethis:NSNumber*anAccountNumber=[NSNumbernumberWithInt:12345];Account*newAccount=[[Accountalloc]init];[newAccountsetValue:anAccountNumberforKey:@"accountNumber"];NSNumber*anotherAccountNumber=[newAccountvalueForKey:@"accountNumber"];Thoseareequivalentsetsofstatements.Iknowyou"rethinking:wow,butsarcastically.KVCdoesn"tlookallthatuseful.Infact,itlooks"wordy".Butwhenyouwanttochangethingsatruntime,youcandolotsofcoolthingsthataremuchmoredifficultinotherlanguages(butthisisbeyondthescopeofyourquestion).IfyouwanttolearnmoreaboutKVC,therearemanytutorialsifyouGoogleespeciallyatScottStevenson"sblog.Hopethathelps.objectForKey:acceptsanyobjectasakey,notjuststrings.TheonlyrequirementisthatthekeysupporttheNSCopyingprotocol.WhenyoudovalueForKey:youneedtogiveitanNSString,whereasobjectForKey:cantakeanyNSObjectsubclassasakey.ThisisbecauseforKey-ValueCoding,thekeysarealwaysstrings.Infact,thedocumentationstatesthatevenwhenyougivevalueForKey:anNSString,itwillinvokeobjectForKey:anywayunlessthestringstartswithan@,inwhichcaseitinvokes[supervalueForKey:],whichmaycallvalueForUndefinedKey:whichmayraiseanexception.此段是說C字串無效,必須是@開頭的字串

  • 中秋節和大豐收的關聯?
  • 四大名著的說法,從什麼時候開始有的?