    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: An Introduction to Objective-C</title>
        <link>https://members.accu.org/index.php/journals/783</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 17, #1 - Feb 2005 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c98/">171</a>
                    (9)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c98-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c98+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;An Introduction to Objective-C</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 February 2005 13:16:10 +00:00 or Thu, 03 February 2005 13:16:10 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Type
Introspection</h2>
<h3>Part 4 - Some Further Topics</h3>
</div>
<p>Objective-C has a rich set of methods by which the contents and
capabilities of an object can be queried. <tt class=
"classname">NSObject</tt> implements:</p>
<p><tt class="literal">(Class)class</tt> returns the class object
for the receiver's class.</p>
<p><tt class="literal">(Class)superclass</tt> returns the class
object for the class from which the receiver inherits.</p>
<p><tt class="literal">(BOOL)isMemberOfClass:(Class)class</tt>
returns YES if the argument to the method is an instance of the
specified class.</p>
<p><tt class="literal">(BOOL)isKindOfClass:(Class)class</tt>
returns YES if the argument to the method is an instance of the
specified class or of a class that inherits from it.</p>
<p><tt class="literal">(BOOL)respondsToSelector:(SEL)aSelector</tt>
returns YES if the receiving object is capable of handling a
certain message.</p>
<p>There are also functions to query classes for their instance
variables and class and instance methods, and methods can be
queried for information about their arguments.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e52" id="d0e52"></a>Extensions</h2>
</div>
<p>NeXT and Apple have extended the language specified by Cox in
&quot;Object-Oriented Programming, an Evolutionary Approach&quot; with
categories, protocols and, most recently, Java-style
exception-handling, thread synchronisation and support for invoking
methods in remote processes. The last two are considered too
specialised to be dealt with in this article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e57" id="d0e57"></a>Categories</h2>
</div>
<p>Categories add new functionality to an already existing class.
They are particularly useful where you are using a third-party
class library and you are not free to amend that library's source
code. One solution to this problem is to derive a new class from
the one you need to extend, but this may require detailed knowledge
of the superclass, and inheritance notoriously breaks
encapsulation. To create a category, you declare interface and
implementation sections as shown in the pseudocode below:</p>
<p>In the header file, <tt class=
"filename">CategoryName.h</tt>:</p>
<pre class="programlisting">
#import &quot;ClassName.h&quot;
@interface ClassName (CategoryName)
method declarations
@end
</pre>
<p>In <tt class="filename">CategoryName.m</tt>:</p>
<pre class="programlisting">
#import &quot;CategoryName.h&quot;
@implementation ClassName (CategoryName)
method definitions
@end
</pre>
<p>A class has a size that is fixed at compilation time, so it is
not possible to add instance variables to an existing class in this
manner; the only way to do this is to use inheritance.</p>
<p>The file <tt class="filename">StringTokenizer.m</tt> contains
the following lines:</p>
<pre class="programlisting">
// Create a category to forward-declare private
// method in order to avoid compiler warnings about
// undeclared methods.
@interface StringTokenizer (Private)
- (void)skipDelimiters;
@end
</pre>
<p>Since -<tt class="methodname">skipDelimiters</tt> is not meant
to be directly accessible to the users of a class, it would be
inappropriate to declare it in <tt class=
"filename">StringTokenizer.h</tt>, and so I have created a category
in the implementation file to contain declarations of private
methods. This is not strictly necessary, as an Objective-C compiler
emits a warning, not an error, when it is required to compile a
message to an undeclared method, and since the programmer knows
that the method has been defined, the program would work perfectly
well without such a category declaration.</p>
<p>Categories can also be used to split up the implementation of a
class into separate units, with perhaps each having its own
implementation file; this would facilitate the development of
classes to which more than one programmer contributes. They can
also be used to declare informal protocols, of which more
below.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e95" id="d0e95"></a>Protocols</h2>
</div>
<p>Protocols involve the declaration of a list of methods whose
implementation is deferred to any class that chooses to implement
them. If a class adopts an informal protocol, it can choose which
methods to implement, whereas with a formal protocol,
implementations of all the methods listed must reside either in the
class itself or in its superclasses. This is a way of associating
classes that share similar behaviour but are not closely related in
the inheritance hierarchy.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e100" id="d0e100"></a>Informal
Protocols</h3>
</div>
<p>There is little language support for informal protocols, but in
the Foundation framework, informal protocols are often declared as
a category of the root class, <tt class="classname">NSObject</tt>.
Here is the list of methods in GNUStep's version of Foundation for
the informal protocol <tt class="classname">NSKeyValueCoding</tt>,
which defines a mechanism in which the properties of an object are
accessed indirectly by name (or key), rather than directly through
invocation of an accessor method or as instance variables:</p>
<pre class="programlisting">
@interface NSObject (NSKeyValueCoding)
+ (BOOL) accessInstanceVariablesDirectly;
+ (BOOL) useStoredAccessor;
- (id) handleQueryWithUnboundKey: (NSString*)aKey;
- (void) handleTakeValue: (id)anObject
                    forUnboundKey: (NSString*)aKey;
- (id) storedValueForKey: (NSString*)aKey;
- (void) takeStoredValue: (id)anObject forKey:
                    (NSString*)aKey;
- (void) takeStoredValuesFromDictionary:
                    (NSDictionary*)aDictionary;
- (void) takeValue: (id)anObject forKey:
                    (NSString*)aKey;
- (void) takeValue: (id)anObject forKeyPath:
                    (NSString*)aKey;
- (void) takeValuesFromDictionary:
                    (NSDictionary*)aDictionary;
- (void) unableToSetNilForKey: (NSString*)aKey;
- (id) valueForKey: (NSString*)aKey;
- (id) valueForKeyPath: (NSString*)aKey;
- (NSDictionary*) valuesForKeys: (NSArray*)keys;
@end
</pre>
<p>Any object that derives from <tt class="classname">NSObject</tt>
can select from this list which methods it needs to implement in
order to acquire appropriate key-value coding functionality.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e118" id="d0e118"></a>Formal
Protocols</h3>
</div>
<p>Formal protocols are enforced by the language. They are declared
as in the following pseudocode:</p>
<pre class="programlisting">
@protocol ProtocolName
method declarations
@end
</pre>
<p>Here is a declaration for the <tt class=
"classname">NSCoding</tt> protocol for the serialisation
('flattening') and deserialisation (reconstruction) of objects
associated with archiving from disk or some other form of
distribution to another address space.</p>
<p>@protocol NSCoding - (void) encodeWithCoder: (NSCoder*)aCoder; -
(id) initWithCoder: (NSCoder*)aDecoder; @end</p>
<p>If the class <tt class="classname">Person</tt> needed to be
stored on disk, it would adopt the <tt class=
"classname">NSCoding</tt> protocol:</p>
<pre class="programlisting">
#import &lt;Foundation/Foundation.h&gt;
@interface Person : NSObject &lt;NSCoding&gt;
{
  NSString *name;
  NSString *address;
}
// Accessor methods
- (NSString *)name;
- (NSString *)address;
- (void)setName:(NSString *)aName;
- (void)setAddress:(NSString *)anAdress;
// Other methods ...
@end

@implementation Person
// Accessor methods
- (NSString *)name {return name;}
- (NSString *)address {return address;}
- (void)setName:(NSString *)aName
{
  [aName retain];
  [name release];
  name = aName;
}
- (void)setAddress:(NSString *)anAdress
{
  [anAddress retain];
  [address release];
  address = anAdress;
}
// NSCoding methods
- (void) encodeWithCoder: (NSCoder*)aCoder
{
  [super encodeWithCoder:coder];
  [aCoder encodeObject:name];
  [aCoder encodeObject:address];
}
- (id) initWithCoder: (NSCoder*)aDecoder;
{
  self = [super initWithCoder:coder];
  name = [[coder decodeObject] retain];
  address = [[coder decodeObject] retain];
  return self;
}
// Called when the object is deallocated
- (void) dealloc {[name release]; [address release]}
@end
</pre>
<p>Formal protocols are equivalent to interfaces in Java; indeed,
the designers of Java have copied this idea from Objective-C.
Assuming that Foundation had been implemented in C++ you would
write something like the following abstract class definition:</p>
<pre class="programlisting">
class NSObject;
class NSCoding {
  virtual void encodeWithCoder(NSCoder&amp; aCoder) = 0;
  virtual NSObject* decodeWithCoder(
                         const NSCoder&amp; aCoder) = 0;
};

class Person : public NSObject, public NSCoding {
  NSString *name_, *address_;
public:
  // Accessor functions
  NSString* name();
  void setName(const NSString* aName);
  NSString* address();
  void setAddress(const NSString* anAddress);
  // NSCoder virtual functions
  void encodeWithCoder(NSCoder&amp; aCoder);
  NSObject* decodeWithCoder(const NSCoder&amp; aCoder);
  // Other functions ...
  // Called when the object is deallocated
  virtual ~Person();
};
</pre>
<p>The implemention of these methods in C++ is left to the reader's
imagination.</p>
<p>Unlike C++, neither Objective-C nor Java implements multiple
inheritance, and so these languages need a separate mechanism for
adopting protocols.</p>
<p>It cannot always be known at run-time whether a particular
object implements a formal protocol; it can be tested in the
following way:</p>
<pre class="programlisting">
if([anObject conformsTo:@protocol(NSCoding)])
   [anObject encodeWithCoder:myCoder];
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e154" id=
"d0e154"></a>Exceptions</h2>
</div>
<p>Simple exception-handling code could be written as follows;</p>
<pre class="programlisting">
Cup *cup = [[Cup alloc] init];
@try {
  [cup fill];
}
@catch (NSException *exception) {
  NSLog(@&quot;main: Caught %@: %@&quot;, [exception name], [exception reason]);
}
@finally {
  [cup release];
}
</pre>
<p>Code that might throw an exception is enclosed within a
<tt class="literal">@try</tt> block, and the exception should be
caught in a <tt class="literal">@catch</tt> block. A <tt class=
"literal">@finally</tt> block contains code that must be executed
whether an exception is thrown or not.</p>
<p><tt class="classname">Cup</tt>'s <tt class=
"methodname">fill</tt> method might throw an exception like
this:</p>
<pre class="programlisting">
NSException *exception = [NSException exceptionWithName:@&quot;HotTeaException&quot;
         reason:@&quot;The tea is too hot&quot; userInfo:nil];
@throw exception;
</pre>
<p>ny kind of Objective-C object can be thrown.</p>
<p>An exception can be re-thrown by means of <tt class=
"literal">@throw</tt> without an argument.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
