Objective C Lecture Notes

how to start programming in objective c and programming in c objective type questions and answers pdf free download
AndyCole Profile Pic
AndyCole,United Kingdom,Professional
Published Date:09-07-2017
Your Website URL(Optional)
2 Chapter 1 Introduction When the iPhone was released in 2007, developers clamored for the opportunity to develop applications for this revolutionary device.At first,Apple did not welcome third- party application development.The company’s way of placating wannabe iPhone devel- opers was to allow them to develop web-based applications.A web-based application runs under the iPhone’s built-in Safari web browser and requires the user to connect to the website that hosts the application in order to run it. Developers were not satisfied with the many inherent limitations of web-based applications, and Apple shortly there- after announced that developers would be able to develop so-called native applications for the iPhone. A native application is one that resides on the iPhone and runs under the iPhone’s op- erating system, in the same way that the iPhone’s built-in applications (such as Contacts, Stocks, and Weather) run on the device.The iPhone’s OS is actually a version of Mac OS X, which meant that applications could be developed and debugged on a MacBook Pro, for example. In fact,Apple soon provided a powerful Software Development Kit (SDK) that allowed for rapid iPhone application development and debugging.The availability of an iPhone simulator made it possible for developers to debug their applications directly on their development system, obviating the need to download and test the program on an actual iPhone or iPod Touch device. With the introduction of the iPad in 2010,Apple started to genericize the terminol- ogy used for the operating system and the SDK that now support different devices with different physical sizes and screen resolutions.The iOS SDK allows you to develop ap- plications for any iOS device and as of this writing, iOS 4 is the current release of the operating system. What You Will Learn from This Book When I contemplated writing a tutorial on Objective-C, I had to make a fundamental decision.As with other texts on Objective-C, I could write mine to assume that the reader already knew how to write C programs. I could also teach the language from the perspective of using the rich library of routines, such as the Foundation and UIKit frameworks. Some texts also take the approach of teaching how to use the development tools, such as the Mac’s Xcode and the tool formerly known as Interface Builder to de- sign the UI. I had several problems adopting this approach. First, learning the entire C language be- fore learning Objective-C is wrong. C is a procedural language containing many features that are not necessary for programming in Objective-C, especially at the novice level. In fact, resorting to some of these features goes against the grain of adhering to a good ob- ject-oriented programming methodology. It’s also not a good idea to learn all the details of a procedural language before learning an object-oriented one.This starts the program- mer in the wrong direction, and gives the wrong orientation and mindset for fostering a good object-oriented programming style. Just because Objective-C is an extension to the C language doesn’t mean you have to learn C first.How This Book Is Organized 3 So I decided neither to teach C first nor to assume prior knowledge of the language. Instead, I decided to take the unconventional approach of teaching Objective-C and the underlying C language as a single integrated language, from an object-oriented program- ming perspective.The purpose of this book is as its name implies: to teach you how to program in Objective-C 2.0. It does not profess to teach you in detail how to use the de- velopment tools that are available for entering and debugging programs, or to provide in- depth instructions on how to develop interactive graphical applications.You can learn all that material in greater detail elsewhere, after you’ve learned how to write programs in Objective-C. In fact, mastering that material will be much easier when you have a solid foundation of how to program in Objective-C.This book does not assume much, if any, previous programming experience. In fact, if you’re a novice programmer, with some dedication and hard work you should be able to learn Objective-C as your first program- ming language. Other readers have been successful at this, based on the feedback I’ve re- ceived from the previous editions of this book. This book teaches Objective-C by example.As I present each new feature of the lan- guage, I usually provide a small complete program example to illustrate the feature. Just as a picture is worth a thousand words, so is a properly chosen program example.You are strongly encouraged to run each program (all of which are available online) and compare the results obtained on your system to those shown in the text. By doing so, you will learn the language and its syntax, but you will also become familiar with the process of compiling and running Objective-C programs. How This Book Is Organized This book is divided into three logical parts. Part I,“The Objective-C 2.0 Language,” teaches the essentials of the language. Part II,“The Foundation Framework,” teaches how to use the rich assortment of predefined classes that form the Foundation framework. Part III,“Cocoa, Cocoa Touch, and the iOS SDK,” gives you an overview of the Cocoa and Cocoa Touch frameworks and then walks you through the process of developing a simple iOS application using the iOS SDK. A framework is a set of classes and routines that have been logically grouped together to make developing programs easier. Much of the power of programming in Objective-C rests on the extensive frameworks that are available. Chapter 2,“Programming in Objective-C,” begins by teaching you how to write your first program in Objective-C. Because this is not a book on Cocoa or iOS programming, graphical user interfaces (GUIs) are not extensively taught and are hardly even mentioned until Part III. So an ap- proach was needed to get input into a program and produce output. Most of the exam- ples in this text take input from the keyboard and produce their output in a window pane: a Terminal window if you’re using gcc from the command line, or a debug output pane if you’re using Xcode.4 Chapter 1 Introduction Chapter 3,“Classes, Objects, and Methods,” covers the fundamentals of object-oriented programming.This chapter introduces some terminology, but it’s kept to a minimum. I also introduce the mechanism for defining a class and the means for sending messages to instances or objects. Instructors and seasoned Objective-C programmers will notice that I use static typing for declaring objects. I think this is the best way for the student to get started because the compiler can catch more errors, making the programs more self-documenting and encouraging the new programmer to explicitly declare the data types when they are known.As a result, the notion of the id type and its power is not fully explored until Chapter 9,“Polymorphism, Dynamic Typing, and Dynamic Binding.” Chapter 4,“Data Types and Expressions,” describes the basic Objective-C data types and how to use them in your programs. Chapter 5,“Program Looping,” introduces the three looping statements you can use in your programs:for,while, and do. Making decisions is fundamental to any computer programming language. Chapter 6, “Making Decisions,” covers the Objective-C language’s if and switch statements in detail. Chapter 7,“More on Classes,” delves more deeply into working with classes and objects. Details about methods, multiple arguments to methods, and local variables are discussed here. Chapter 8,“Inheritance,” introduces the key concept of inheritance.This feature makes the development of programs easier because you can take advantage of what comes from above. Inheritance and the notion of subclasses make modifying and extending existing class definitions easy. Chapter 9 discusses three fundamental characteristics of the Objective-C language. Polymorphism, dynamic typing, and dynamic binding are the key concepts covered here. Chapters 10–13 round out the discussion of the Objective-C language, covering issues such as initialization of objects, blocks, protocols, categories, the preprocessor, and some of the underlying C features, including functions, arrays, structures, and pointers.These un- derlying features are often unnecessary (and often best avoided) when first developing object-oriented applications. It’s recommended that you skim Chapter 13,“Underlying C Features,” the first time through the text and return to it only as necessary to learn more about a particular feature of the language. Chapter 13 also introduces a recent addi- tion to the C language known as blocks.This should be learned after you learn about how to write functions, since the syntax of the former is derived from the latter. Part II begins with Chapter 14,“Introduction to the Foundation Framework,” which gives an introduction to the Foundation framework and how to use its voluminous documentation. Chapters 15–19 cover important features of the Foundation framework.These include number and string objects, collections, the file system, memory management, and the process of copying and archiving objects. By the time you’re done with Part II, you will be able to develop fairly sophisticated programs in Objective-C that work with the Foundation framework.Acknowledgments 5 Part III starts with Chapter 20,“Introduction to Cocoa and Cocoa Touch” Here you’ll get a quick overview of the frameworks that provide the classes you need to develop so- phisticated graphical applications on the Mac and on your iOS devices. Chapter 21,“Writing iOS Applications,” introduces the iOS SDK and the UIKit framework.This chapter illustrates a step-by-step approach to writing a simple iOS appli- cation, followed by a more sophisticated calculator application that enables you to use your iPhone to perform simple arithmetic calculations with fractions. Because object-oriented parlance involves a fair amount of terminology,Appendix A, “Glossary,” provides definitions of some common terms. Appendix B,“Address Book Source Code,” gives the source code listing for two classes that are developed and used extensively in Part II of this text.These classes define address card and address book classes. Methods enable you to perform simple operations such as adding and removing address cards from the address book, looking up someone, listing the contents of the address book, and so on. After you’ve learned how to write Objective-C programs, you can go in several direc- tions.You might want to learn more about the underlying C programming language—or you might want to start writing Cocoa programs to run on Mac OS X, or develop more sophisticated iOS applications. Support If you go to classroomM.com/objective-c you’ll find a forum rich with content.There you can get source code (note that you won’t find the “official” source code for all the examples there, as I am a firm believer that a big part the learning process occurs when you type in the program examples yourself and learn how to identify and correct any errors.), answers to exercises, errata, quizzes, and pose questions to me and fellow forum members.The forum has turned into a rich community of active members who are happy to help other members solve their problems and answer their questions. Please go, join, and participate Acknowledgments I would like to acknowledge several people for their help in the preparation of the first edition of this text. First, I want to thank Tony Iannino and Steven Levy for reviewing the manuscript. I am also grateful to Mike Gaines for providing his input. I’d also like to thank my technical editors, Jack Purdum (first edition) and Mike Trent. I was lucky enough to have Mike review the first two editions of this text. He provided the most thorough review of any book I’ve ever written. Not only did he point out weaknesses, but he was also generous enough to offer his suggestions. Because of Mike’s comments in the first edition, I changed my approach to teaching memory management and tried to make sure that every program example in this book was “leak free.” Mike also provided invaluable input for my chapter on iPhone programming.6 Chapter 1 Introduction From the first edition, Catherine Babin supplied the cover photograph and provided me with many wonderful pictures to choose from. Having the cover art from a friend made the book even more special. I am so grateful to Mark Taber (for all editions) from Pearson for putting up with all delays and for being kind enough to work around my schedule and to tolerate my consis- tent missing of deadlines while working on the second and third editions. From Pearson I’d also like to thank my development editor, Michael Thurston, my copy editor, Krista Hansing, and my project editor, Mandie Frank, who expertly managed the mad dash to the finish line. I am extremely grateful to Michael de Haan and Wendy Mui for doing an incredible, unsolicited job proofreading the second edition (and thanks Wendy for your work on the third edition as well). Their meticulous attention to detail has resulted in a list of both typographical and substantive errors that have been addressed in the second printing. Publishers take note: these two pairs of eyes are priceless Finally, I’d like to thank the members of the forum at classroomM.com/objective-c for all their feedback, support, and kind words. Stephen G. Kochan February 201112 Chapter 2 Programming in Objective-C Table 2.1 Common Filename Extensions Extension Meaning .c C language source file .cc, .cpp C++ language source file .h Header file .m Objective-C source file .mm Objective-C++ source file .pl Perl source file .o Object (compiled) file Returning to your Xcode project window, the right pane shows the contents of the file called main.m, which was automatically created for you as a template file by Xcode, and which contains the following lines: // // main.m // prog1 // // Created by Steve Kochan on 1/30/11. // Copyright 2011 ClassroomM, Inc.. All rights reserved. // import Foundation/Foundation.h int main (int argc, const char argv) NSAutoreleasePool pool = NSAutoreleasePool alloc init; // insert code here... NSLog ("Hello World"); pool drain; return 0; You can edit your file inside this window . Make changes to the program shown in the Edit window to match Program 2.1.The lines that starts with two slash characters (//) are called comments; we talk more about comments shortly. Your program in the edit window should now look like this (don’t worry if your com- ments don’t match): Program 2.1 // First program example import Foundation/Foundation.h int main (int argc, const char argv) 16 Chapter 2 Programming in Objective-C First, you need to enter the lines from Program 2.1 into a file.You can begin by creat- ing a directory in which to store your program examples.Then you must run a text edi- tor, such as vi or emacs, to enter your program: sh-2.05a mkdir Progs Create a directory to store programs in sh-2.05a cd Progs Change to the new directory sh-2.05a vi main.m Start up a text editor to enter program Note In the previous example and throughout the remainder of this text, commands that you, the user, enter are indicated in boldface. For Objective-C files, you can choose any name you want; just make sure the last two characters are .m.This indicates to the compiler that you have an Objective-C program. After you’ve entered your program into a file (and we’re not showing the edit com- mands to enter and save your text here), you can use the GNU Objective-C compiler, which is called gcc, to compile and link your program.This is the general format of the gcc command: gcc –framework Foundation files -o progname This option says to use information about the Foundation framework: -framework Foundation Just remember to use this option on your command line. files is the list of files to be compiled. In our example, we have only one such file, and we’re calling it main.m. progname is the name of the file that will contain the executable if the program compiles without any errors. We’ll call the program prog1; here, then, is the command line to compile your first Objective-C program: gcc –framework Foundation main.m -o prog1 Compile main.m & call it prog1 The return of the command prompt without any messages means that no errors were found in the program. Now you can subsequently execute the program by typing the name prog1 at the command prompt: prog1 Execute prog1 sh: prog1: command not found This is the result you’ll probably get unless you’ve used Terminal before.The UNIX shell (which is the application running your program) doesn’t know where prog1 is located (we don’t go into all the details of this here), so you have two options: One is to precede the name of the program with the characters ./ so that the shell knows to look in the current directory for the program to execute.The other is to add the directory inExplanation of Your First Program 17 which your programs are stored (or just simply the current directory) to the shell’s PATH variable. Let’s take the first approach here: ./prog1 Execute prog1 2008-06-08 18:48:44.210 prog17985:10b Programming is fun You should note that writing and debugging Objective-C programs from the terminal is a valid approach. However, it’s not a good long-term strategy. If you want to build Mac OS X or iOS applications, there’s more to just the executable file that needs to be “packaged” into an application bundle. It’s not easy to do that from the Terminal applica- tion, and it’s one of Xcode’s specialties.Therefore, I suggest you start learning to use Xcode to develop your programs.There is a learning curve to do this, but the effort will be well worth it in the end. Explanation of Your First Program Now that you are familiar with the steps involved in compiling and running Objective-C programs, let’s take a closer look at this first program. Here it is again: // // main.m // prog1 // // Created by Steve Kochan on 1/30/11. // Copyright 2011 ClassroomM, Inc.. All rights reserved. // import Foundation/Foundation.h int main (int argc, const char argv) NSAutoreleasePool pool = NSAutoreleasePool alloc init; NSLog ("Programming is fun"); pool drain; return 0; In Objective-C, lowercase and uppercase letters are distinct.Also, Objective-C doesn’t care where on the line you begin typing—you can begin typing your statement at any position on the line.You can use this to your advantage in developing programs that are easier to read. The first seven lines of the program introduce the concept of the comment.A comment statement is used in a program to document a program and enhance its readability. Com- ments tell the reader of the program—whether it’s the programmer or someone else18 Chapter 2 Programming in Objective-C whose responsibility it is to maintain the program—just what the programmer had in mind when writing a particular program or a particular sequence of statements. You can insert comments into an Objective-C program in two ways. One is by using two consecutive slash characters (//).The compiler ignores any characters that follow these slashes, up to the end of the line. You can also initiate a comment with the two characters / and .This marks the beginning of the comment.These types of comments have to be terminated.To end the comment, you use the characters and /, again without any embedded spaces.All charac- ters included between the opening / and the closing / are treated as part of the com- ment statement and are ignored by the Objective-C compiler.This form of comment is often used when comments span many lines of code, as in the following: / This file implements a class called Fraction, which represents fractional numbers. Methods allow manipulation of fractions, such as addition, subtraction, etc. For more information, consult the document: /usr/docs/classes/fractions.pdf / Which style of comment you use is entirely up to you. Just note that you can’t nest the / style comments. Get into the habit of inserting comment statements in the program as you write it or type it into the computer, for three good reasons. First, documenting the program while the particular program logic is still fresh in your mind is far easier than going back and rethinking the logic after the program has been completed. Second, by inserting com- ments into the program at such an early stage of the game, you can reap the benefits of the comments during the debug phase, when program logic errors are isolated and debugged. Not only can a comment help you (and others) read through the program, but it also can help point the way to the source of the logic mistake. Finally, I haven’t yet dis- covered a programmer who actually enjoys documenting a program. In fact, after you’ve finished debugging your program, you will probably not relish the idea of going back to the program to insert comments. Inserting comments while developing the program makes this sometimes tedious task a bit easier to handle. This next line of Program 2.1 tells the compiler to locate and process a file named Foundation.h: import Foundation/Foundation.h This is a system file—that is, not a file that you created.import says to import or include the information from that file into the program, exactly as if the contents of the file were typed into the program at that point.You imported the file Foundation.h because it has information about other classes and functions that are used later in the program. In Program 2.1, this line specifies that the name of the program is main: int main (int argc, const char argv)Explanation of Your First Program 19 main is a special name that indicates precisely where the program is to begin execu- tion.The reserved word int that precedes main specifies the type of value main returns, which is an integer (more about that soon).We ignore what appears between the open and closed parentheses for now; these have to do with command-line arguments, a topic we address in Chapter 13,“Underlying C Language Features.” Now that you have identified main to the system, you are ready to specify precisely what this routine is to perform.This is done by enclosing all the program statements of the routine within a pair of curly braces. In the simplest case, a statement is just an expression that is terminated with a semicolon.The system treats all the program statements included between the braces as part of the main routine. Program 2.1 has four statements. The first statement in Program 2.1 reads NSAutoreleasePool pool = NSAutoreleasePool alloc init; It reserves space in memory for an autorelease pool.We discuss this thoroughly in Chapter 17,“Memory Management.” Xcode puts this line into your program automati- cally as part of the template, so just leave it there for now. The next statement specifies that a routine named NSLog is to be invoked, or called.The parameter, or argument, to be passed or handed to the NSLog routine is the following string of characters: "Programming is fun" Here, the sign immediately precedes a string of characters enclosed in a pair of double quotes. Collectively, this is known as a constant NSString object. Note If you have C programming experience, you might be puzzled by the leading character. Without that leading character, you are writing a constant C-style string; with it, you are writing an NSString string object. More on this topic in Chapter 15. The NSLog routine is a function in the Objective-C library that simply displays or logs its argument (or arguments, as you will see shortly). Before doing so, however, it displays the date and time the routine is executed, the program name, and some other numbers we don’t describe here.Throughout the rest of this book, we don’t bother to show this text that NSLog inserts before your output. You must terminate all program statements in Objective-C with a semicolon (;).This is why a semicolon appears immediately after the closed parenthesis of the NSLog call. Before you exit your program, you should release the allocated memory pool (and objects that are associated with it) with a line such as the following: pool drain; Again, Xcode automatically inserts this line into your program for you.Again, we defer detailed explanation of what this does until later.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.