неділя, 9 жовтня 2011 р.

Objective-c та @"А за м'ютебл, м'ютебл, а за м'ютебл, м'ютебл, а за м'ютебл, м'ютебл, ось і кінчився хеш, ні ні ні, зачекай, ось і ще один м'ютебл, а за м'ютебл, м'ютебл... "

Перед тим, як почати говорити про об'єкти, я вирішив, що дуже важливо буде поговорити хоч трішки про масиви, строки та хеш-таблиці. Багато хто може запитати, що за дурнувата назва статті, зараз спробую все пояснити.
Objective-c має такі класи: 
NSString (робота з строками), NSInteger , NSNumber(робота з числами в загальному), NSArray(робота з масивами), NSDictionary(робота з хешом). 
 NSDictionary містить набір ключів та значить, які прив'язуюються до цього ключа, впринципі це невеличка база данних, причому до ключа можна прив"язувать все завгодно, чого тільки душа забажає.

А деякі з них мають своїх наслідників з приставкою Mutable:
NSMutableArray, NSMutableDictionary, NSMutableString. За допомогою цієї приставки можна себе почувати набагато комфортніше з Objective-c, так як мова стає набагато гібучішою, в плані реалізації. Тепер Ви спокійно можите змінювати розмір своєї строки, це щось схоже на StringBuffer з Java. З масивами схожа ситуація - вони перетворюються на динамічні масиви, а до хешу можна додавати нові ключі і значення.

#import <Foundation/Foundation.h>

int main (void)
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    //заводимо змінні
    NSEnumerator * enumerator;
    NSInteger      i ;
    id             key;
    NSString     * value ;
    //Приклад заповнення форматованої строки   
    NSString * str  = [ NSString stringWithFormat :  @"2 x 2 = %i", 4];

   //Вивід отриманої строки
    NSLog (@"Answer is  = %@", str);   
    // Приклад заповнення масиву
    NSArray *arr = [NSArray arrayWithObjects: @"one", @"two", @"three", nil];

   //Вивід отриманого масиву
    NSLog(@"Array conatines %@",arr);
    //Вивід масиву по-елементно
    for (i = 0; i < [arr count]; i++)
        NSLog(@"%@",[arr objectAtIndex: i] );
    //Виділення пам'яті під динамічну хеш-таблицю       
    NSMutableDictionary * SQL = [[NSMutableDictionary alloc] init];

   //Готуємо масив з назвами країн, який віддамо в словник 
    NSArray * countrys = [[NSArray alloc] initWithObjects:@"USA", @"England",@"Ukraine",@"Russia",@"Poland", @"Belarus", nil]; 

//Готуємо масив з назвами столиць країн, який віддамо в словник  
    NSArray * capitals = [[NSArray alloc] initWithObjects:@"Washington", @"London",@"Kyiv",@"Moscow",@"Warsaw", @"Minsk", nil];    

   //Готуємо масив з к-стю населення в столицях, який віддамо в словник
    NSArray * populationCapitals = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt: 5894121], [NSNumber numberWithInt: 7825200],
    [NSNumber numberWithInt: 2797553], [NSNumber numberWithInt: 10470318], [NSNumber numberWithInt: 1716855], [NSNumber numberWithInt: 1836808],nil];
//very important NIL!!!!    
 
    //Готуємо масив з к-стю населення країн, який віддамо в словник  
    NSArray * populationCountry = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt: 308688000], [NSNumber numberWithInt: 60980304],
    [NSNumber numberWithInt: 45778500], [NSNumber numberWithInt: 142008000], [NSNumber numberWithInt: 38364700], [NSNumber numberWithInt: 9663000],nil];
   
//Готуємо масив з назвами грошових одиниць країн, який віддамо в словник
    NSArray * money  = [[NSArray alloc] initWithObjects:@"dolar", @"pound",@"grivna",@"rybl",@"zloty", @"BYR rybl 'zaichik'", nil];
  //Заповнюэмо наший ловник
   [SQL initWithObjectsAndKeys: countrys, @"Country",capitals, @"Capital",     populationCapitals , @"Population at capital",
    populationCountry, @"Population at country", money, @"National money", nil];
   //Виводимо результат в лог
    NSLog(@"SQL = %@", SQL);

//Приклад, як можна достукатися до певної комірки, конкретного ключа (в даному випадку беремо розмір масиву,який знаходиться за ключем "Country")
    NSLog(@"Object for key %@ Number %i",[ SQL objectForKey: @"Country"] , [[ SQL objectForKey: @"Country"] count]);
   //Змінна, з необхідним для нас  значенням
    NSInteger selectedPlace  = [[ SQL objectForKey: @"Country"] indexOfObject: @"Ukraine"];
    //1ший метод отримання значень

   //Створюємо масив в який зберігаємо назви всих ключів,які в нас є
    NSArray *keys = [[NSArray alloc] initWithArray: [SQL allKeys]];
    NSLog(@"KEYS = %@", keys);
   //Користуючись ключами, вибираємо всі знаення, які нам необхідні
    for (i = 0; i < [keys count]; i++)
        {
          value =[[NSString alloc] initWithString:(NSString *)[keys objectAtIndex: i]];
          NSLog(@"Key %@ = Value %@", [ keys objectAtIndex: i],  [[ SQL objectForKey: value] objectAtIndex: selectedPlace]);       
          [value release];
        }
        //2-ий спосіб використовуємо ітератор
 enumerator = [SQL keyEnumerator];
    // В циклы проходимо по всих необхыдних для нас значеннях
while ((key = [enumerator nextObject])) {
  NSLog(@"%@ = %@", key,  [[ SQL objectForKey: key] objectAtIndex: selectedPlace]);
}

//Очистка пам'яті
    [keys release];
    [money release];
    [populationCountry release];
    [countrys release];
    [SQL release];
   
   
    [pool drain];
   
    return (0);   
}

Якщо ви все правильно зробите, то результат має бути таким:

gcc `gnustep-config --objc-flags` -lgnustep-base Mutable.m -o Mutable
>gcc `gnustep-config --objc-flags` -lgnustep-base Mutable.m -o Mutable
>Exit code: 0
./Mutable
>./Mutable




2011-10-09 12:54:31.769 Mutable[2986] Answer is  = 2 x 2 = 4
2011-10-09 12:54:31.819 Mutable[2986] Array conatines (one, two, three)
2011-10-09 12:54:31.820 Mutable[2986] one
2011-10-09 12:54:31.820 Mutable[2986] two
2011-10-09 12:54:31.820 Mutable[2986] three
2011-10-09 12:54:31.820 Mutable[2986] SQL = {Capital = (Washington, London, Kyiv, Moscow, Warsaw, Minsk); Country = (USA, England, Ukraine, Russia, Poland, Belarus); "National money" = (dolar, pound, grivna, rybl, zloty, "BYR rybl 'zaichik'"); "Population at capital" = (5894121, 7825200, 2797553, 10470318, 1716855, 1836808); "Population at country" = (308688000, 60980304, 45778500, 142008000, 38364700, 9663000); }
2011-10-09 12:54:31.820 Mutable[2986] Object for key (USA, England, Ukraine, Russia, Poland, Belarus) Number 6
2011-10-09 12:54:31.820 Mutable[2986] KEYS = (Country, "Population at country", "National money", "Population at capital", Capital)
2011-10-09 12:54:31.821 Mutable[2986] Key Country = Value Ukraine
2011-10-09 12:54:31.821 Mutable[2986] Key Population at country = Value 45778500
2011-10-09 12:54:31.821 Mutable[2986] Key National money = Value grivna
2011-10-09 12:54:31.821 Mutable[2986] Key Population at capital = Value 2797553
2011-10-09 12:54:31.821 Mutable[2986] Key Capital = Value Kyiv
2011-10-09 12:54:31.821 Mutable[2986] Country = Ukraine
2011-10-09 12:54:31.821 Mutable[2986] Population at country = 45778500
2011-10-09 12:54:31.821 Mutable[2986] National money = grivna
2011-10-09 12:54:31.821 Mutable[2986] Population at capital = 2797553
2011-10-09 12:54:31.821 Mutable[2986] Capital = Kyiv
Для ефектифвності коду, я підготував оновлений словник:


v. 1. 0. 1
(~THE_DICTIONARY_OF_OBJECTIVE_C_WORDS~)

gcc `gnustep-config --objc-flags` -lgnustep-base <name file>.m -o <name .o file> ./<name file >  Example:  gcc `gnustep-config --objc-flags` -lgnustep-base hello.m -o hello
./hello

. /usr/share/GNUstep/Makefiles/GNUstep.sh

@interface @implementation @end @class @property @protocol @selector @synthesize @private @protected @public
void return BOOL YES NO new unsigned const volatile in out inout bycopy byref oneway self
#pragma
char short int long float double signed unsigned id  drain count
alloc init initWith retain release autorealease

stringWithFormat arrayWithObjects


NSArray
initWithArray: initWithArray:copyItems: initWithContentsOfFile: initWithContentsOfURL: initWithObjects: initWithObjects:count:
 indexOfObject:  indexOfObject:inRange: indexOfObjectIdenticalTo: indexOfObjectIdenticalTo:inRange: indexOfObjectPassingTest:
 indexOfObjectWithOptions:passingTest: indexOfObjectAtIndexes:options:passingTest: indexesOfObjectsPassingTest: indexesOfObjectsWithOptions:passingTest:
 indexesOfObjectsAtIndexes:options:passingTest: indexOfObject:inSortedRange:options:usingComparator:
componentsSeparatedByString:  componentsJoinedByString: 
 NSDictionary
 dictionary dictionaryWithContentsOfFile:  dictionaryWithContentsOfURL: dictionaryWithDictionary:  dictionaryWithObject:forKey: dictionaryWithObjects:forKeys:
 dictionaryWithObjects:forKeys:count:  dictionaryWithObjectsAndKeys:  initWithContentsOfFile: initWithContentsOfURL: initWithDictionary: initWithDictionary:copyItems:
 initWithObjects:forKeys: initWithObjects:forKeys:count: initWithObjectsAndKeys: objectForKey: getObjects:andKeys: valueForKey:
 NSNumber: (NSArray *)allKeys
 numberWithChar: numberWithInt: numberWithFloat: numberWithBool




 NSString
 string init initWithBytes:length:encoding: initWithBytesNoCopy:length:encoding:freeWhenDone: initWithCharacters:length:initWithCharactersNoCopy:length:freeWhenDone:
initWithString: initWithCString:encoding: initWithUTF8String: initWithFormat: initWithFormat:arguments: initWithFormat:locale:initWithFormat:locale:arguments:
initWithData:encoding: stringWithFormat: localizedStringWithFormat: stringWithCharacters:length: stringWithString: stringWithCString:encoding:
stringWithUTF8String: stringWithCString: Deprecated in Mac OS X v10.4 stringWithCString:length: Deprecated in Mac OS X v10.4
initWithCString: Deprecated in Mac OS X v10.4 initWithCString:length: Deprecated in Mac OS X v10.4 initWithCStringNoCopy:length:freeWhenDone: Deprecated in Mac OS X v10.4
 NSMutableString
appendFormat: appendString: deleteCharactersInRange:  insertString:atIndex:  replaceCharactersInRange:withString:
replaceOccurrencesOfString:withString:options:range: setString:


 NSLog
 NSAffineTransform NSAppleEventDescriptor NSAppleEventManager NSAppleScript NSArchiver NSArray
 NSAssertionHandler NSAttributedString NSAutoreleasePool NSBlockOperation NSBundle NSCache
 NSCachedURLResponse NSCalendar NSCharacterSet NSClassDescription NSCloneCommand NSCloseCommand
 NSCoder NSComparisonPredicate NSCompoundPredicate NSCondition NSConditionLock NSConnection NSCountCommand
 NSCountedSet NSCreateCommand NSData NSDataDetector NSDate NSDateComponents NSDateFormatter NSDecimalNumber
 NSDecimalNumberHandler NSDeleteCommand NSDeserializer NSDictionary NSDirectoryEnumerator NSDistantObject
 NSDistantObjectRequest NSDistributedLock NSDistributedNotificationCenter NSEnumerator NSError NSException
 NSExistsCommand NSExpression NSFileHandle NSFileManager NSFileWrapper NSFormatter NSGarbageCollector NSGetCommand
 NSHashTable NSHost NSHTTPCookie NSHTTPCookieStorage NSHTTPURLResponse NSIndexPath NSIndexSet NSIndexSpecifier
 NSInputStream NSInvocation NSInvocationOperation NSInteger NSKeyedArchiver NSKeyedUnarchiver NSLinguisticTagger
 NSLocale NSLock NSLogicalTest NSMachBootstrapServer NSMachPort NSMapTable NSMessagePort NSMessagePortNameServer
 NSMetadataItem NSMetadataQuery NSMetadataQueryAttributeValueTuple NSMetadataQueryResultGroup NSMethodSignature
 NSMiddleSpecifier NSMoveCommand NSMutableArray NSMutableAttributedString NSMutableCharacterSet NSMutableData
 NSMutableDictionary NSMutableIndexSet NSMutableSet NSMutableString NSMutableURLRequest NSNameSpecifier
 NSNetService NSNetServiceBrowser NSNotification NSNotificationCenter NSNotificationQueue NSNull
 NSNumber NSNumberFormatter NSObject NSOperation NSOperationQueue NSOrderedSet NSOrthography
 NSOutputStream NSPipe NSPointerArray NSPointerFunctions NSPort NSPortCoder NSPortMessage NSPortNameServer
 NSPositionalSpecifier NSPredicate NSProcessInfo NSPropertyListSerialization NSPropertySpecifier NSProtocolChecker NSProxy
 NSQuitCommand NSRandomSpecifier NSRangeSpecifier NSRecursiveLock NSRegularExpression NSRelativeSpecifier NSRunLoop NSScanner
 NSScriptClassDescription NSScriptCoercionHandler NSScriptCommand NSScriptCommandDescription NSScriptExecutionContext NSScriptObjectSpecifier
 NSScriptSuiteRegistry NSScriptWhoseTest NSSerializer NSSet NSSetCommand NSSocketPort NSSocketPortNameServer NSSortDescriptor
 NSSpecifierTest NSSpellServer NSStream NSString NSTask NSTextCheckingResult NSThread NSTimer NSTimeZone NSUnarchiver NSUndoManager
 NSUniqueIDSpecifier NSURL NSURLAuthenticationChallenge NSURLCache NSURLConnection NSURLCredential
 NSURLCredentialStorage NSURLDownload NSURLHandle NSURLProtectionSpace NSURLProtocol NSURLRequest NSURLResponse
 NSUserDefaults NSValue NSValueTransformer NSWhoseSpecifier NSXMLDocument NSXMLDTD NSXMLDTDNode NSXMLElement
 NSXMLNode NSXMLParser  NSCoding NSComparisonMethods NSConnectionDelegate NSCopying NSDecimalNumberBehaviors
 NSErrorRecoveryAttempting NSFastEnumeration NSFileManagerDelegate NSKeyedArchiverDelegate NSKeyedUnarchiverDelegate
 NSKeyValueCoding NSKeyValueObserving NSLocking NSMachPortDelegate NSMetadataQueryDelegate NSMutableCopying
 NSNetServiceBrowserDelegate NSNetServiceDelegate NSObjCTypeSerializationCallBack NSObject NSPortDelegate
 NSScriptingComparisonMethods NSScriptKeyValueCoding NSScriptObjectSpecifiers NSSpellServerDelegate
 NSStreamDelegate NSURLAuthenticationChallengeSender NSURLHandleClient NSURLProtocolClient NSXMLParserDelegate
*/

Немає коментарів:

Дописати коментар