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".
  • Objective-C - Data Encapsulation, Synthesized Accessors and Dot Notation - Techotopia
    by property directives import Foundation Foundation h interface BankAccount NSObject double accountBalance long accountNumber property double accountBalance property long accountNumber void displayAccountInfo end Note that because the two properties are of different data types double and long it was necessary to declare them on separate property lines Had they been of the same data type we could have placed them on the same line separated by commas property int x y Having declared the properties the next step is to declare that synthesized accessor methods are required This is performed in the implementation section of the class definition implementation BankAccount synthesize accountBalance accountNumber void displayAccountInfo NSLog Account Number ld has a balance of f accountNumber accountBalance end Note that regardless of data types of the properties involved the variable names may be placed on a single synthesize line as illustrated above Having created the accessors the question that now arises is what these methods are named In assigning a name to a synthesized accessor method Objective C takes the name of the instance variable for example accountBalance capitalizes the first letter AccountBalance and then pre fixes it with set setAccountBalance For example BankAccount account1 account1 BankAccount alloc account1 account1 init account1 setAccountBalance 1500 53 account1 setAccountNumber 34543212 Direct Access to Encapsulated Data Data encapsulation encourages the use of methods to get and set the values of instance variables in a class Now is probably the time to point out this is a guideline rather than a rule In fact it is quite common for developers to want to directly access an instance variable without having to go through an accessor method The Objective C syntax for referencing an instance variable is as follows classinstance variablename Taking our BankAccount example therefore we could get the value of our accountNumber instance variable and assign it to a variable named balance1 as follows double balance1 account1 accountBalance Objective C and Dot Notation google IOSBOX google Those familiar with object oriented programming in Java C or C are probably reeling a little from the syntax used in Objective C They are probably thinking life was much easier when they could just use something called dot notation to set and get the values of instance variables The good news is that one of the features introduced into version 2 0 of Objective C is support for dot notation Dot notation involves accessing an instance variable by specifying a class instance followed by a dot followed in turn by the name of the instance variable or property to be accessed classinstance property For example to the get current value of our accountBalance instance variable double balance1 account1 accountBalance Dot notation can also be used to set values of instance properties account1 accountBalance 6789 98 A key point to understand about dot notation is that it only works for instance variables for which synthesized accessor methods have been declared If you attempt to use dot notation to access an instance variable for which no synthesized accessor is

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


  • Objective-C Inheritance - Techotopia
    void setAccountBalance double x accountBalance x double getAccountBalance return accountBalance void setAccountNumber long y accountNumber y long getAccountNumber return accountNumber void displayAccountInfo NSLog Account Number ld has a balance of f accountNumber accountBalance end As we can see from the declaration this class is a subclass of the NSObject base class and contains a number of instance variables and instance methods Though this is a somewhat basic class it does everything necessary if all you need it to do is store an account number and account balance Suppose however that in addition to the BankAccount class you also needed a class to be used for savings accounts A savings account will still need to hold an account number and a current balance and methods will still be needed to access that data One option would be to create an entirely new class one that duplicates all of the functionality of the BankAccount class together with the new features required by a savings account A more efficient approach would be to create a new class that is a subclass of the BankAccount class The class will then inherit all the features of the BankAccount class but can then be extended to add the additional functionality required by a savings account To create a subclass of BankAccount that we will call SavingsAccount we simply write the appropriate interface and implementation structure this time specifying BankAccount instead of NSObject as the parent class inheritance passes down through all levels of the class hierarchy so SavingsAccount will still inherit from NSObject via the BankAccount parent class interface SavingsAccount BankAccount end implementation SavingsAccount end Note that although we have yet to add any instance variables or methods the class has actually inherited all the methods and variables of the parent BankAccount class We could therefore create an instance of the SavingAccount class and set variables and call methods in exactly the same way did with the BankAccount class in An Overview of Objective C Object Oriented Programming That said we haven t really achieved anything unless we actually take steps to extend the class Extending the Functionality of a Subclass So far we have been able to create a subclass that contains all the functionality of the parent class including the functionality the parent class inherited from its parent class and so on In order for this exercise to make sense however we now need to extend the subclass so that it has the features we need to make it useful for storing savings account information To do this we simply add the instance variables and methods that provide the new functionality just as we would for any other class we might wish to create interface SavingsAccount BankAccount float interestRate float calculateInterest void setInterestRate float y end implementation SavingsAccount float calculateInterest return interestRate accountBalance void setInterestRate float y interestRate y end With these changes made we now have a class that inherits the features of the BankAccount class but now has an additional instance variable

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

  • Pointers and Indirection in Objective-C - Techotopia
    is once again displayed When compiled and executed the following output is displayed Before call to function myvar 10 After call to function myvar 10 Clearly even though the value passed through to myFunction was increased by 20 the value of myvar remained unchanged This is because what was passed through as an argument to myFunction was the value of myvar not the myvar variable itself Therefore in myFunction we were simply working on a constant value of 10 that had absolutely no connection to the original myvar variable In order to be able to work on the actual variable in the function we need to use something called indirection An Overview of Indirection Indirection involves working with pointers to the location of variables and objects rather than the contents of those items In other words instead of working with the value stored in a variable we work with a pointer to the memory address where the variable is located Pointers are declared by prefixing the name with an asterisk character For example to declare a pointer to our myvar variable we would write the following code int myvar 10 int myptr In the above example we have declared our myvar variable and then declared a variable named myptr as being of type pointer to an integer Having declared both our variable and our pointer we now need to assign the address of our variable to the pointer The address of a variable is referenced by prefixing it with the ampersand character We can therefore extend our example to assign the address of the myvar variable to the myptr variable int myvar 10 int myptr myptr myvar We now have now implemented a level of indirection by creating a pointer to our variable As such we can now pass this pointer through as an argument to our function such that we will be able to work on the actual variable rather than just the value 10 of the variable In order to access the value of a variable using a pointer to that variable we prefix the pointer variable name with an asterisk When we do this we are telling the compiler we want to work with the contents of the variable or object at the memory address contained within the pointer int myvar 10 int myptr myptr myvar myptr myptr 15 Similarly we can modify our function to accept a pointer to an integer and perform the addition on that variable As such we can now modify our previous program as follows import Foundation Foundation h void myFunction int i i i 10 int main int argc const char argv autoreleasepool int myvar 10 int myptr myptr myvar NSLog Before call to function myvar i myvar myFunction myptr NSLog After call to function myvar i myvar return 0 Now because we are passing through a pointer to myvar when we call the function and have modified the function to work with the contents of the variable the output clearly

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

  • Objective-C Dynamic Binding and Typing with the id Type - Techotopia
    arguments to functions or methods It is much easier to write a single general purpose function or method that can handle an object from any class than to write a different function or method for each class in an application This is where the concept of dynamic typing is used Dynamic typing allows us to declare a variable that is capable of storing any type of object regardless of its class origins This is achieved using the Objective C id type The id type is a special general purpose data type that can be assigned an object of any type In the following dynamic typing example we create a variable of type id named object1 and then assign a BankAccount object to it We then call a method on the object before releasing it We then use the same object1 variable to store an object of type Customer Info and call a method on that object id object1 object1 SavingsAccount alloc init object1 setAccount 4543455 andBalance 3010 10 object1 CustomerInfo alloc init object1 displayInfo Dynamic Binding Dynamic typing is about using the id type to provide a variable that can be used to store objects of any type during program execution Dynamic binding takes this one step further by allowing methods on an object stored in an id variable to be called without prior knowledge of the type of object currently assigned to the variable Suppose for example that we want to write a function that is passed an object Within the function the displayInfo method of that object is called Without dynamic typing and dynamic binding we would need to write one function for each class type that we wanted to be able to handle With Objective C s dynamic typing and binding we can declare the object argument as being type id thereby allowing us to pass any object through to the function Secondly we can then rely on dynamic binding to ensure that when we call the object s displayInfo method within the function we are calling it on the correct object i e the one that was passed through as an argument Let s begin by writing our function void objDisplay id object object displayInfo As we can see from the above code the function is called objDisplay it accepts an object as the single argument which is assigned to an id type variable and then makes a call to the displayInfo method of the object We can now combine this function with a main routine that creates two different object types and then calls the objDisplay function for each int main int argc const char argv autoreleasepool id object1 object1 SavingsAccount alloc init object1 setAccount 4543455 andBalance 3010 10 objDisplay object1 object1 CustomerInfo alloc init objDisplay object1 return 0 Note that the objDisplay function makes the assumption that the object it has been passed actually has a method named displayInfo This highlights a shortcoming of dynamic typing and binding in that the compiler will be

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

  • Objective-C Variable Scope and Storage Class - Techotopia
    j in for loop is 16 2009 10 19 15 09 39 879 t 8130 10b Variable j in for loop is 17 2009 10 19 15 09 39 880 t 8130 10b Variable j in for loop is 18 2009 10 19 15 09 39 880 t 8130 10b Variable j in for loop is 19 2009 10 19 15 09 39 881 t 8130 10b Variable j outside for loop is 54321 Function Scope Objective C code is typically structured into a number of classes and code units called functions for more details on functions see the chapter entitled An Overview of Objective C Functions In terms of variable scope functions are really little more than statement blocks in that they are encapsulated in braces and variables declared within those braces are local to that function block The following example is intended to illustrate this concept and contains two functions named main and multiply respectively import Foundation Foundation h int main int argc const char argv autoreleasepool int j 10 int k 20 int result result mutliply return 0 int multiply return j k An attempt to compile the above code example will result in a compiler error similar to the following In function multiply error j undeclared first use in this function error Each undeclared identifier is reported only once error for each function it appears in error k undeclared first use in this function The reason for this error is that variables j and k are declared in the main function and are therefore local to that function As such these variables are not visible to the multiply function resulting in an error when we try to reference them If we wanted to have access to the values of those variables we would have to pass them through as arguments to the multiply function for details on function arguments refer to An Overview of Objective C Functions or specify them as global or static variables discussed below As with block scope it is possible to have multiple variables with the same name inside a single function as long as each instance appears within its own local scope For example we can add a while loop to our main that has its own local variable also named j int main int argc const char argv autoreleasepool int j 10 int k 20 int result while k 0 int j 0 j k k return 0 Global Scope A variable that has global scope is potentially accessible to code anywhere else in an Objective C program regardless of whether the code is in a separate file to the one in which the variable is declared Global variables are declared outside of any statement blocks and are typically placed near the top of a source file The following is a code listing from an Objective C source file named main m import Foundation Foundation h int myVar 321 int main int argc const char argv autoreleasepool NSLog myVar i

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

  • An Overview of Objective-C Functions - Techotopia
    functions are global by default After the different source files have been compiled to object code a tool called the linker then performs the task of resolving undefined symbols in each object file When it finds a call to an undefined function in one object file it searches the other object files that comprise the code and any libraries specified until it finds it If no match is found the linker will fail with an undefined symbol error Functions are called using the following syntax function name arg1 arg2 For example to call a function named sayhello that takes no arguments and returns no value we would write the following code sayhello To call a function called multiply that take two arguments and returns an integer we might write the following code int result result multiply 10 20 In the above example we have created a new variable called result and then used the assignment operator to store the result returned by the multiply function when it is passed the numbers 10 and 20 as arguments Function Prototypes Where a function is declared in relation to where it is called from is a significant factor In the same way that most cultures read a page from top to bottom a compiler reads an Objective C source file from top to bottom If the compiler comes across a call to a function before it has found the function declaration it has to make assumptions about the type of result that function returns The default assumption is that the function will return an int Having made this assumption if when the compiler finally reaches the function declaration an error will have to reported if it is found to return a data type other than an int To see this in action try compiling the following code import Foundation Foundation h int main int argc const char argv autoreleasepool float result result multiply 10 20 return 0 float multiply int x int y return x y When an attempt to compile the above code is made the compilation will fail with the following message warning implicit declaration of function multiply is invalid in C99 Wimplicit function declaration error conflicting types for multiply main m 8 18 note previous implicit declaration is here The compiler is complaining because it had assumed when the function was called at line 10 that it returned an int because up until that point it had not found a function declaration to tell it otherwise Having made this assumption it then found the function declaration and discovered it actually returned a float thereby causing a conflict There are two solutions to this problem One is to always declare function before they are called import Foundation Foundation h float multiply int x int y return x y int main int argc const char argv autoreleasepool float result result multiply 10 20 return 0 This is a work around for simple cases but can quickly become unmanageable in larger application code

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

  • Objective-C Enumerators - Techotopia
    default the first value corresponds to 0 the second to 1 and so on It is also possible to specify the values used by each value name enum name value name 1 value1 value name 2 value2 For example we can specify an enumeration for the days of the week enum daysofweek monday tuesday wednesday thursday friday saturday sunday In the above construct monday is equal to 0 tuesday is 1 and so on If we specify a number for just one entry the remaining values will follow on from that number For example enum daysofweek monday 1 tuesday wednesday thursday friday saturday sunday In this case monday will be 1 tuesday will be 2 etc Alternatively we can specify a value for each entry in the enumeration enum temperature cold 5 warm 50 hot 95 Creating and Using an Enumeration Having declared an enumeration the next step is to declare a variable of that type For example to create a variable called currentTemp from our temperature enumerator type we would write the following code enum temperature currentTemp Now that we have created a variable based on our enumerator data type we can try setting a value using one of the value names and then displaying the current value of the variable int currentTemp hot NSLog Current temperature is i currentTemp When compiled and executed the above code will output the following 2009 10 21 10 25 46 640 t 11525 10b Current temperature is 95 As we can see although we assigned hot to our currentTemp variable Objective C translated it to the corresponding number 95 If we attempt to assign a value using an undefined name as follows the code will fail to compile with a tepid undeclared error message currentTemp tepid We can however bypass this system

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

  • An Overview of the Objective-C Foundation Framework - Techotopia
    full history of how this came to be refer to the chapter entitled The History of Objective C Due to the fact that the Foundation Framework started life of part of NeXTstep the classes that comprise this framework all begin with the letters NS You will recall that when we created our first class in An Overview of Objective C Object Oriented Programming we derived our class from NSObject NSObject is a part of the Foundation Framework and as you become more familiar with the framework you will learn that most Foundation classes are derived from this class In this and subsequent chapters we will look in more detail at some of the other classes provided by the framework Including the Foundation Headers In previous chapters we have been including the header files for the Foundation Framework in our examples This is achieved using the following line of code import Foundation Foundation h In fact if we don t want to have to worry about including the header file for each Foundation class we wish to use in a code file this is all we need to do Alternatively we can selectively include the header files for only the classes we intend to use For example the following code imports only the headers we need import Foundation NSObject h import Foundation NSString h import Foundation NSAutoreleasePool h int main int argc const char argv autoreleasepool NSString myString Hello return 0 Finding the Foundation Framework Documentation A detailed overview of every class and method in the Foundation Framework is beyond the scope of this book and would be largely redundant given that this information is already provided by Apple in various locations Instead this book will focus on teaching you how to use the most common Foundation classes to work with

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



  •