archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Working with String Objects in Objective-C - Techotopia
    What we have achieved here is to create two variables string1 and string2 that point to the memory location of the same string object This is because the before the variable names in the declarations indicates that this is a pointer to an object not an actual object Any time that we access the object referenced by either of these pointers we will in fact be accessing the same object To prove this we can make a change using the string2 reference and then display the string associated with both the string1 and string1 object pointers NSMutableString string1 NSMutableString string2 string1 NSMutableString stringWithString This is a string string2 string1 string2 appendString and it is mine NSLog string1 string1 NSLog string2 string2 The above code will display the following output proving that both string1 and string2 point to the same object since only one reference was modified yet both show the change 2009 11 03 14 35 37 731 t 32239 10b string1 This is a string and it is mine 2009 11 03 14 35 37 732 t 32239 10b string2 This is a string and it is mine To actually copy one string object to another string object we must use stringWithString method the NSMutableString class NSMutableString string1 NSMutableString string2 string1 NSMutableString stringWithString This is a string Initialize string1 string2 NSMutableString stringWithString string1 Copy string1 object to string2 string2 appendString and it is mine Modify string2 NSLog string1 string1 NSLog string2 string2 When executed the appended text appears only in the object referenced by string2 since string2 now references a different object to that referenced by string1 2009 11 03 14 42 10 426 t 32263 10b string1 This is a string 2009 11 03 14 42 10 427 t 32263 10b string2 This is a string and it is mine Searching for a Substring A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string This can be achieved using the rangeOfString method This method returns a structure of type NSRange The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match NSString string1 The quick brown fox jumped NSRange match match string1 rangeOfString brown fox NSLog match found at index lu match location NSLog match length lu match length The NSLog call will display the location and length of the match Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1 As such the location in our example will be 10 and the length will be 9 In the event that no match is found the rangeOfString method will set the location member of the NSRange structure to NSNotFound For example NSString string1 The quick brown fox jumped NSRange match match string1 rangeOfString brown dog if match location NSNotFound NSLog Match

    Original URL path: http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C (2016-02-13)
    Open archived version from archive


  • Understanding Objective-C Number Objects - Techotopia
    numberWith Unsigned Type The full list of creation and initialization methods is as follows numberWithBool numberWithChar numberWithDouble numberWithFloat numberWithInt numberWithInteger numberWithLong numberWithLongLong numberWithShort numberWithUnsignedChar numberWithUnsignedInt numberWithUnsignedInteger numberWithUnsignedLong numberWithUnsignedLongLong numberWithUnsignedShort Because these are class methods rather than instance methods they are called on the class rather than on an existing object For example to create an NSNumber object called myFloat configured to hold a float value we could write the following code NSNumber myFloat myFloat NSNumber numberWithFloat 10 09 Once executed the above code will create a new NSNumber object and assign the floating point value of 10 09 to it Getting the Value of a Number Object The current value stored in a number object can be obtained using one of a number of retrieval instance methods The type of value retrieved depends on the method used The full list of retrieval instance methods is as follows google IOSBOX google boolValue charValue decimalValue doubleValue floatValue intValue integerValue longLongValue longValue shortValue unsignedCharValue unsignedIntegerValue unsignedIntValue unsignedLongLongValue unsignedLongValue unsignedShortValue For example we can extend our example to retrieve and display the value stored in our number object as follows NSNumber myFloat float floatvalue myFloat NSNumber numberWithDouble 10 09 floatvalue myFloat floatValue NSLog Value f floatvalue Note that the method used to retrieve the value stored in a number object must match the method used to store the object An attempt for example to retrieve a char from an object initialized as double will provide an unexpected result Comparing Number Objects To compare the values stored in two number objects it is necessary to use either the isEqualToNumber or compare methods These are both instance variables and as such are called on one object instance passing through the second object as an argument isEqualToNumber returns a Boolean value depending on whether the two objects

    Original URL path: http://www.techotopia.com/index.php/Understanding_Objective-C_Number_Objects (2016-02-13)
    Open archived version from archive

  • Working with Objective-C Array Objects - Techotopia
    array that will allow the array contents to be modified we need to use the NSMutableArray class NSMutableArray myColors myColors NSMutableArray arrayWithObjects Red Green Blue Yellow nil Finding out the Number of Elements in an Array The number of objects in an array referred to as elements can be identified using the count instance method of the NSArray class NSArray myColors myColors NSArray arrayWithObjects Red Green Blue Yellow nil NSLog Number of elements in array lu myColors count When executed the above code will output the following Number of elements in array 4 Accessing the Elements of an Array Object The objects contained in an array are given index positions beginning at position zero Each element may be accessed by passing the required index position through as an argument to the NSArray objectAtIndex instance method We can therefore now extend our array example to display each element using the count method to identify in advance how many elements there are to display NSArray myColors int i int count myColors NSArray arrayWithObjects Red Green Blue Yellow nil count myColors count for i 0 i count i NSLog Element i i myColors objectAtIndex i When run the above code will display each element in the array object Element 0 Red Element 1 Green Element 2 Blue Element 3 Yellow Accessing Array Elements using Fast Enumeration The technique for accessing all the array elements using a for loop as described in the previous section is a little ungainly Another easier mechanism for accessing element in an array involves something called fast enumeration Fast enumeration simply requires that a variable be declared to hold each array element and then referenced in the for loop NSArray myColors NSString color myColors NSArray arrayWithObjects Red Green Blue Yellow nil for color in myColors NSLog Element color Adding Elements to an Array Object New elements may be added to a mutable array object using the addObject instance method of the NSMutableArray class For example to declare and initialize an array and then later add new element object the following code might be used NSMutableArray myColors myColors NSMutableArray arrayWithObjects Red Green Blue Yellow nil myColors addObject Indigo myColors addObject Violet Inserting Elements into an Array The previous method appends new objects onto the end of an array It is also possible to insert new objects at specific index points in an array object using the insertObject instance method This method accepts as arguments the object to be inserted and the index position at which the insertion is to take place NSMutableArray myColors int i int count myColors NSMutableArray arrayWithObjects Red Green Blue Yellow nil myColors insertObject Indigo atIndex 1 myColors insertObject Violet atIndex 3 count myColors count for i 0 i count i NSLog Element i i myColors objectAtIndex i When we compile and run the code the following output confirms that the new objects were indeed inserted at the specified index positions Element 0 Red Element 1 Indigo Element 2 Green Element 3 Violet Element 4 Blue Element

    Original URL path: http://www.techotopia.com/index.php/Working_with_Objective-C_Array_Objects (2016-02-13)
    Open archived version from archive

  • Objective-C Dictionary Objects - Techotopia
    be created as follows NSDictionary bookListing NSDictionary dictionary Similarly an empty mutable dictionary may be created as follows NSMutableDictionary bookListing NSMutableDictionary dictionary Initializing and Adding Entries to a Dictionary Object Each key value pair contained within a dictionary is referred to as an entry Once a relationship between a key and a value has been established that relationship cannot subsequently be modified New entries are added to a dictionary using the setObject instance method This method takes as its arguments an object and a corresponding key NSMutableDictionary bookListing NSMutableDictionary dictionary bookListing setObject Wind in the Willows forKey 100 432112 bookListing setObject Tale of Two Cities forKey 200 532874 bookListing setObject Sense and Sensibility forKey 202 546549 bookListing setObject Shutter Island forKey 104 109834 In the above example the bookListing dictionary is initialized with four book names with corresponding reference codes to act as keys It is also possible to create and initialize a dictionary with a number of key value pairs using the dictionaryWithObjectsAndKeys class method For example an alternative to the above code is as follows NSDictionary bookListing NSDictionary dictionaryWithObjectsAndKeys Wind in the Willows 100 432112 Tale of Two Cities 200 532874 Sense and Sensibility 202 546549 Shutter Island 104 109834 nil Dictionaries may also be initialized using keys and values contained in arrays using the arrayWithObjects method NSArray objectsArray NSArray arrayWithObjects Wind in the Willows Tale of Two Cities Sense and Sensibility Shutter Island nil NSArray keysArray NSArray arrayWithObjects 100 432112 200 532874 202 546549 104 109834 nil NSDictionary bookListing NSDictionary alloc initWithObjects objectsArray forKeys keysArray Getting an Entry Count A count of the number of entries in a dictionary can be obtained using the count instance methods NSMutableDictionary bookListing NSMutableDictionary dictionary int count bookListing setObject Wind in the Willows forKey 100 432112 bookListing setObject Tale of Two

    Original URL path: http://www.techotopia.com/index.php/Objective-C_Dictionary_Objects (2016-02-13)
    Open archived version from archive

  • Working with Directories in Objective-C - Techotopia
    objc myapp example m In addition the home directory of the current user can be represented using the tilde character For example the pathname example m references a file named example m located in the home directory of the current user The home directory of another user may be referenced by prefixing the user name with a For example john demo m references a file located in the home directory of a user named john Obtaining a Reference to the Default NSFileManager Object The NSFileManager class contains a class method named defaultManager that is used to obtain a reference to the application s default file manager instance NSFileManager filemgr filemgr NSFileManager defaultManager In the above example we have declared a variable named filemgr to point to an object of type NSFileManager and then requested a pointer to the application s file manager and assigned it to the variable Having obtained the object reference we can begin to use it to work with files and directories Identifying the Current Working Directory The current working directory may be identified using the currentDirectoryPath instance method of our NSFileManager object The current path is returned from the method in the form of an NSString object NSFileManager filemgr NSString currentpath filemgr NSFileManager defaultManager currentpath filemgr currentDirectoryPath NSLog Current directory is currentpath Changing to a Different Directory The current working directory of a running Objective C program can be changed with a call to the changeCurrentDirectoryPath method The destination directory path is passed as an argument to the instance method in the form of an NSString object Note that this method returns a boolean YES or NO result to indicate if the requested directory change was successful for not NSFileManager filemgr NSString currentpath filemgr NSFileManager defaultManager currentpath filemgr currentDirectoryPath NSLog Current directory is currentpath if filemgr changeCurrentDirectoryPath temp mydir NO NSLog Cannot change directory currentpath filemgr currentDirectoryPath NSLog Current directory is currentpath Creating a New Directory A new directory is created using the createDirectoryAtURL instance method this time passing through the through the pathname of the new directory as an argument in the form of an NSURL object This method also takes additional arguments in the form of a set of attributes for the new directory and a Boolean value indicating whether or not intermediate directories should be created if they do not already exist Specifying nil will use the default attributes NSFileManager filemgr filemgr NSFileManager defaultManager NSURL newDir NSURL fileURLWithPath tmp mynewdir filemgr createDirectoryAtURL newDir withIntermediateDirectories YES attributes nil error nil The createDirectoryAtURL method returns a Boolean result indicating the success or otherwise of the operation Deleting a Directory An existing directory may be removed from the file system using the removeItemAtPath method passing though the path of the directory to be removed as an argument NSFileManager filemgr filemgr NSFileManager defaultManager filemgr removeItemAtPath tmp mynewdir handler nil Renaming or Moving a File or Directory An existing file or directory may be moved also known as renaming using the moveItemAtURL method This method takes the source

    Original URL path: http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C (2016-02-13)
    Open archived version from archive

  • Working with Files in Objective-C - Techotopia
    tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed Creating a Symbolic Link A symbolic link to a particular file may be created using the createSymbolicLinkAtPath method This takes as arguments the path of the symbolic link the path to the file to which the link is to refer and an optional NSError object For example the following code creates a symbolic link from tmpUsers demo myfile21 txt that links to the pre existing file tmp myfile txt NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr createSymbolicLinkAtPath tmp myfile2 txt withDestinationPath tmp myfile txt error NULL YES NSLog Link successful else NSLog Link failed NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr createSymbolicLinkAtPath Users demo file1 txt withDestinationPath tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed Reading and Writing Files with NSFileManager The NSFileManager class includes some basic file reading and writing capabilities these capabilities are somewhat limited when compared to the options provided by the NSFileHandle class but can be useful nonetheless Firstly the contents of a file may be read and stored in an NSData object through the use of the contentsAtPath method NSFileManager filemgr NSData databuffer filemgr NSFileManager defaultManager databuffer filemgr contentsAtPath tmp myfile txt Having stored the contents of a file in an NSData object that data may subsequently be written out to a new file using the createFileAtPath method databuffer filemgr contentsAtPath tmp myfile txt filemgr createFileAtPath tmp newfile txt contents databuffer attributes nil google IOSBOX google In the above example we have essentially copied the contents from an existing file to a new file This however gives us no control over how much data is to be read or written and does not allow us to append data to the end of an existing file If the file tmp newfile txt in the above example had already existed it and any data it contained would have been overwritten by the contents of the source file Clearly some more flexible mechanism is required This is provided by the Foundation Framework in the form of the NSFileHandle class Working with Files using the NSFileHandle Class The NSFileHandle class provides a range of methods designed to provide a more advanced mechanism for working with files In addition to files this class can also be used for working with devices and network sockets In the following sections we will look at some of the more common uses for this class Creating an NSFileHandle Object An NSFileHandle object can be created when opening a file for reading writing or updating reading and writing This is achieved using the fileHandleForReadingAtPath fileHandleForWritingAtPath and fileHandleForUpdatingAtPath methods respectively Having opened a file it must subsequently be closed when we have finished working with it using the closeFile method If an attempt to open a file fails for example because an attempt is made to open a non existent file for reading these methods return nil For example the following code excerpt opens a file for reading

    Original URL path: http://www.techotopia.com/index.php/Working_with_Files_in_Objective-C (2016-02-13)
    Open archived version from archive

  • Constructing and Manipulating Paths with NSPathUtilities - Techotopia
    location of this temporary directory Instead it is much safer to use the NSTemporaryDirectory to identify the appropriate directory This function returns the temporary directory for the current user in the form of an NSString object The following code excerpt identifies and then displays the temporary directory using the NSTemporaryDirectory function NSString tempdir tempdir NSTemporaryDirectory NSLog Temp Dir tempdir Getting the Current User s Home Directory The home directory of the current user can be identified using the NSHomeDirectory function This function takes no arguments and returns an NSString object containing the path to the home directory of the user executing the program NSString homedir homedir NSHomeDirectory NSLog Home directory of current user is homedir Getting the Home Directory of a Specified User The home directory of any user on a system can be obtained using the NSHomeDirectoryForUser function This function takes as its sole argument an NSString object containing the name of the user and returns another NSString object containing the corresponding home directory NSString homedir NSString username Paul homedir NSHomeDirectoryForUser username NSLog Home directory of user is username homedir If the requested user does not exist on the system the function will return null Extracting the Filename from a Path As previously discussed a path can consist of the directory in which a file is located followed by the name of the file A common requirement when working with files when programming in any language is to extract just the file name from a path This can easily be achieved using the lastPathComponent method NSString samplepath Users demo objc sample m NSString filename filename samplepath lastPathComponent NSLog lastPathComponent filename When executed the above code excerpt will display the filename part of the path i e sample m Extracting the Filename Extension Filenames with characters after the final character

    Original URL path: http://www.techotopia.com/index.php/Constructing_and_Manipulating_Paths_with_NSPathUtilities (2016-02-13)
    Open archived version from archive

  • Copying Objects in Objective-C - Techotopia
    myString1 mutableCopy On execution of the mutableCopy method in the above example we will have two independent string objects both of which contain the same string Because we used the mutable version of the copy method we will be able to modify the contents of myString2 In doing so no change will occur to myString1 because that is an entirely different object If we attempted to use either of these copying methods on our own classes without implementing the NSCopying protocol the code will fail to run Take for example the BankAccount class created in An Overview of Objective C Object Oriented Programming If we were to create an instance of the class and then try to call the copy methods we would be presented with a runtime error similar to the following BankAccount copyWithZone unrecognized selector sent to instance 0x1034f0 Terminating app due to uncaught exception NSInvalidArgumentException reason BankAccount copyWithZone unrecognized selector sent to instance 0x1034f0 The reason for this error is that the copy and mutableCopy methods inherited from the NSObject class are trying to call a method called copyWithZone Unfortunately we have not yet implmented this object in our BankAccount class The next step therefore is to learn how to write such a class NSCopying Protocol and copyWithZone Method Implementation The first step in implementing the NSCopying protocol is to declare that the class conforms to the protocol This is achieved in the interface section of the class For example interface BankAccount NSObject NSCopying Also in the implementation we need to declare that the class includes a method named copyWithZone that returns a new object and accepts the zone of the source object as an argument The entire interface section of our class will now read as follows interface BankAccount NSObject NSCopying double accountBalance long accountNumber void setAccount long y andBalance double x double getAccountBalance long getAccountNumber void setAccountBalance double x void setAccountNumber long y void displayAccountInfo id copyWithZone NSZone zone end In our implementation section we now need to write the code for our copyWithZone method This method creates a new BankAccount object copies the values of the instance variables in this case accountBalance and accountNumber and returns a pointer to the new object id copyWithZone NSZone zone BankAccount accountCopy BankAccount allocWithZone zone init accountCopy setAccount accountNumber andBalance accountBalance return accountCopy If we now bring this all together we can using successfully utilize the copy method int main int argc const char argv autoreleasepool BankAccount account1 BankAccount account2 account1 BankAccount alloc account1 account1 init account1 setAccountBalance 1500 53 account1 setAccountNumber 34543212 account1 displayAccountInfo account2 account1 copy account2 displayAccountInfo return 0 Now when executed the above code creates a copy of the object referenced by account1 and assigns a pointer to the new object to variable account2 Performing a Deep Copy The copying techniques we have looked at so far in this chapter are referred to as shallow copies This means that if the copy or mutableCopy methods are used to copy an object that itself contains

    Original URL path: http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C (2016-02-13)
    Open archived version from archive



  •