. notes from reading to learn to obj'c .
. the adda compiler is actually translating the adda language to
the preferred language of the intended platform .
. my first such platform will be mac's objective-c with cocoa libraries .]
7.12: biblio:
11.1: Programming in Objective-C 2.0 -- links
11.1: Cocoa Recipes old downloads:
11.2: Cocoa Recipes current downloads:
-- can only be opened in older versions of Xcode.
1.4: addn/dev.mac/bk"c essentials:
. use sizeof {short, int, long, char, unsigned, float, double}
to find impl specifics;
unsigned means unsigned int;
short, int, long may be all the same size .
-- get to know what's 8, 16, 32, 64 .
printf("bytes %3d\n", sizeof( ...))
. a floating point constant
is type double not float .
. negative is an expression not a mere numeric literal .
. you can re-declare math func's to return other types .
. math.h `sqrt returns double
but you can leave out either the header or (double sqrt())
and it will find sqrt,
but will have assumed its the default return type
of int -- not floating point !
. mixed number expression first converts
smaller than int to
int or unsigned (int), short, char;
then smaller to greater
with types ordered as:
. int, unsigned, long, unsigned long, float, double .
. assignments can also do auto casting
but the size of a stacked item can't change
so the item may be destructively shortened;
ie, watch for need to do explicit casting around a
non-double var being assigned a mixed expr;
worse yet,
autocasting doesn't work at all for
param assignments:
do not pass ints to float functions
or to the division operator!
. in c there can be some type checking,
but this is delegated to lint
rather than the compiler .
. lint and cc typically need to have
a parameter for math access:
{cc, lint} my.c -lm
. extern is how to share obj's across files
. a subfile is a sort of module like the
body of a function or declare block .
. a subfile scope means a
decl' in the middle of a file
creates a subfile from that point downward .
. the way to share an external var
is to not label it static
and then in some other scope
you can declare the same var labeled extern;
then those scopes share that var .
. static label on an internal var
means it's virtually a static external;
ie, the scope is -- instead of being a subfile --
rather the body of the function it's internal to .
. unary op's associating right to left means
rightward has higher precedence
which has an unusual result for post increment:
*p++ is *(p++)
++*p is ++(*p)
. an alternative to malloc is
calloc (contiguous alloc)
where instead of alloc'ing each element of an array,
you alloc an entire array at once
when all elements are the same size .
calloc(array`size.unsigned
, element`size.unsigned
) returns (* char) -- old book .
-- using sizeof() returns unsized,
but often the array`size is an int
which should be cast to unsigned
if lint is to stay quiet .
1.8: addn/dev.mac/c`agg support:
. c does not define assignemnnt for structs ?
. this restriction applies only to older compilers .
. notice that often you don't want this anyway
as structs are often for linked structures,
so what simple way is there for the system to decide
whether you should want a shallow vs deep copy?
but still,
surprising you can take size of record
and yet not copy that much;
ie, default could be shallow copy .
1.10:
. not surprising c doesn't copy arrays
because the syntax would be a mess:
A.array means A returns pointer,
then *A means return 1st value of A,
so then need something like ada`s all; eg A[all] .
1.5: bk"intro to obj'c
Three kinds of dynamism are especially importantobj'c/Cocoa gc (garbage collection)
for object-oriented design:
Dynamic typing, waiting until runtime
to determine the class of an object
Dynamic binding, determining at runtime
what method to invoke
Dynamic loading, adding new components
to a program as it runs,
makes applications extensible .
Linking usually precedes loading.
Dynamic loading refers to the process of
separately loading new parts
and linking them dynamically to the parts already running.
Typically, a group of library classes work together
to define a partial program structure
. These classes constitute a software framework (or kit)
. Most garbage collection systems1.18: bk.addn/dev.obj'c:
restrict direct access to memory pointers
. This has the benefit that you never have to be
concerned about memory errors
-- either leaks due to cyclic data structures
or due to the use of a dangling pointer.
The Objective-C language, however,
has no such restrictions on pointer use.
Although a few garbage collection systems
have been developed for use with C,
their assumptions and performance
make them unsuitable for use with Cocoa objects.
Cocoa therefore uses a custom
non-copying conservative gc system
that in normal use brings safety
and a simplified programming model.
Restricted pointer access-languages
allow for fully-automatic gc.
If you program purely in objects,
then garbage collection in Cocoa
can also be fully automatic .
Beyond programming purely in objects, however,
the collector also provides access to a new
collection-based memory allocation system.
Core Foundation objects are also garbage collected,
but you must follow specific rules
to allocate and dispose of them properly
. In order to understand how you can
take advantage of these features,
you need to understand some of the architectural
details described in this document.
. by default, class method return ref to obj"id,
type"id means ref to tagged type,
type"nil is class of null id',
it has the integer val zero,
-- see objc/objc.h
. type tag is called isa .
2.1: avoid file-based security vulnerabilities:
. I'm not sure I get the following;
is it saying there is no way to
make a folder or file private to a process?
Set your process' file code creation mask (umask). check the result codes
to restrict access to files created by your process.
The umask is a bitmask that alters the
default permissions of a new file.
If you set the umask to 0x022, for example,
any new file created by your process
has rw-r--r-- permissions.
When a process calls another process,
the new process inherits the parent process' umask.
Then if
your process calls another process,
the new process creates a file,
and the new process does not reset the umask,
you have
a good chance of having a file that is
not accessible to all users on the system.
of all the routines you call
since a call might fail unexpectedly
esp'ly when working on a file system
on parallel with other agents or users .
When working in a directory to which
your process does not have exclusive access,
you must check to make sure a file
does not exist before you create it
. You must also verify
that the file you intend to access
is the same file you created.
. use routines that operate on
file descriptors rather than pathnames .
Intentionally make separate steps of
{create file
, open file}
so that you can verify
you are opening a file you created
rather than one that already existed.
When checking for existence or status
you must know whether the
function or shell routine you are calling
follows symbolic links.
eg, the C's lstat(symbolic link)
gives the status of the link
whereas some other functions may report
on the link's target file .
Before you read a file,
make sure it has the
owner and permissions you expect
. Be prepared to fail gracefully
(rather than hanging) if it does not.
2.15:
. obj'c has limited tricky subtype checking:
subclasses can override a function
to give it an incompatable inout .
. obj'c has optional exceptions and threading
(ie, use of these features requires a compiler param)
. threading is when 2 processes share the same mem,
distributed processing is always supported
(processes that use separate mem spaces),
remote msg'ing in distributed obj's
can occur indep'ly of threading or tasking,
ie, threading can share either through
mutex code from sync's,
or by proxy obj's from rpc(remote proc calls) .
2.19:
. be aware of how c's type casting works
for converting int's to bool;
it may let you do it implicitely
while still behaving unexpectedly .
. an obj'c "delegate" is a framework slot,
the same as a callback function
that you define for the framework
to customize system operations .
2.20: bk" K&R`C:
. c names are unique 31 char's;
but function and extern names
are unique only to 6 char's
-- depending on the limits of
your system's assembler and linker .
. {short, int} are atleast 16bit,
and at most the size of long;
long is atleast 32bit .
2.28:
. for a (char to int).conversion to be portable,
specify whether the char is { signed, unsigned}
when storing non-char data there .
3.1: bk K&R`C:
. chars (bytes) are coerced in arithmetic expr's
so its important not to let them
slide into those without specifying
whether they are {signed, unsigned} .
3.4:
. the math functions expect both ( include math.h)
and a signature that states inout types;
then this relaxes need for
explicit casting of arg to double
for lib`math functions .
bit twiddling idioms:
. (~077 & x) sets last 6bits to zero
independent of int size .
-- esp'ly usefulness as
right-shifting negatives is not portable .
. to get what you expect,
you'd need to make it positive before the shift
and then redo the sign after .
sci:
. is it always true that a left shift is a mult?
[...: yes, by definition]
what is going on in big vs little endian?
. a portable way to get /n/ bits is
. if the arithmetic is 2's complement
then the right-most bit can be zeroed by:
(x) & (x-1) .
sci:
. useful to know for efficient bit counting ?
[2010.1.17: book of answers:
. count how many times you can do x`& (x-1)
before x becomes zero .
]
3.4: c`s conditional expression:
(truth)?(return for true): (return for false)
is a function
and c functions must have a static known return type,
so in the case of numbers,
the returns for both truth cases
must be in the same type class cluster;
eg, if the cases are {integer, float}
then the coercion rule`s advice to the compiler
is that this instance of the ?:-function
is returning float .
3.7: comma operator/2 uses:
. comma operator is used in macros
where a multi-step operation
has to be a single expression;
and, as a set notation,
for places that expect a stmt followed by (;)
those places can have (..., ..., ...;) .
. the c goto was primarily a
primitive exception system;
and for nested loops,
to break or continue deeper than current loop .
3.14:
. while (extern symbol) says find it elsewhere
(static symbol) says the symbol is local to file
meaning not bindable by an extern .
. all file-level symbols are ever-existing;
[existing atleast until main's termination?]-2010.1.17
having static locals (those local to a functions
or other blocks, rather than at file-level),
is a way to say ever-existing and local .
[this differs from my prev'understanding,
but seems obvious now]
. the scope of a file-level symbol
is from {def, decl} on downward;
[you might call that subfile scoping,
as it creates a subfile by not applying file-wide .]
. top-level symbols (both external and static),
must be init'd with a compiler-eval'able expr .
. register var's are like auto
in that they don't make sense being at top level .
. the reason static symbols are called such
is for involving non-dynamic (ie, static) allocation;
storage is created at compile time [or link time]-2010.1.16
and doesn't change after that .
. #undef does an un-#define
and is meant to be used along with a decl'
to insure that the declared symbol is
existing as a function
rather than as a macro .
. c typing for ptr is read like so:
for the example ( int *ptr: ),
* is a deref'operator;
and, derefing the ptr gets an int,
so ptr must be a pointer .
*p++ means *(p++)
-- right-to-left assoc' for all unaries .
. one reason c has string be null-terminated,
is to make quick work of substrings
[and it can be more space-efficient .]-2010.1.16
. another purpose of substring is to
index backwards, eg, ptr[-2] is possible
if the a function is handed
the address of the middle of an array .
. a string literal is translated to
a ptr to a static address
and so can be given to a function`arg
of type (char *p) or (char p[]) .
3.15:
. ptr arithmetic includes one beyond the end;
eg, for ar[size]
you can loop
. sizeof(obj).size_t .
. type casting can treat a ptr to one type
as a ptr to another .
3.16: c`idiom for ptr:
. target string copy looks like equality test:
while(*p1++ = *p2++);
-- this says assign one char
then incr' both pointers for the next assign;
the assignment returns to the transfered value,
and during a c`string traverse,
there will eventually be a null char
indicating [end of str]
which the assignment functions to the while.loop
thereby terminating the loop
since a null char is interpreted as false .
. c stack idiom:
push(x): *stack++ = x .
pop(&x): x = *--stack .
3.19:
. to avoid complicated recursive type decl's,
build these structs in small steps
using the typedef operator .
. sizeof(type) also works as
sizeof var -- without paren's .
. within the unix command line,
the idea behind dashing param's
is that command is a function taking an arg,
whereas other optional param's can be thought of as
providing a diffn't function
where the -params are part of the function`name,
eg, cmd-p1-p2 (arg)
can be said in unix as:
cmd -p1 -p2 arg
. some lib'functions have a return type of (void *),
but that is really a generic:
when used, you're expected to type cast the call
showing what type of pointer you're assigning it to .
. use typedef to stay portable:
int, long, short
should be replaced with z8, z16, z32,
3.25:
. the default compile produces both the obj file (.o)
and an exe'able (named a.out
cc -c ... is how to make object files without an exe'able
cc -S ... will emit asm (.s) instead of obj modules
then separate compilation means
cc will handle any mix of {.c .s .o} files
. to produce an exe'able (.out)
one of the files needs to include main()
. to rename a.out use cc -o myrunname
. cc -p will make the profiler available;
after any exe'ing use (prof myexename)
to get a profile listing from the latest exe'ing .
3.27:
exit() is main's return stmt:
. the returning values of main()
-- or other c functions (esp'ly libraries) --
may be giving status .
. exit(x) is both flushing file`buffers
and returning x:
. a return of zero indicates operation was normal,
and then abnormals can be cased
and used as exception signals .
. in main which is always a proc,
(return x) is equ' to exit(x) .
. besides undef, another way to
redef a function that's impl'd as a macro
is to never reuse a library function's name,
so you have to know everything that's in
what you include;
but what about implied includes?
aren't there those?
. if inconvenient
do your code in macros that will wrap
uniquely identifying inconvenient names .
. stdio is for high-level inout,
fcntl is for low-level .
. mac#iphone encourages use of mysql db for data storage .
3.29: bk"c
. c`float-> int ? float is truncated .
c`integral promotion:
{char, short , bit-field, enum} -> int;
but for other not an int`subset ?
these discretes get promoted to unsigned int .
. number conversions can get tricky due to
impl-dep defs of subtypes
and whether your enum's fit in the impl's int .
. per impl,
work with types you know the size of .
. declare all types,
the default decl is int -- an impl-dep size .
. when not using a function`s param or return
do type it void .
. if not using an expression`s return,
do cast in void .
. make sure sizeof can get size of both
the ptr and its object
can get a (ptr -> int).conversion
but size of int for storing ptr value
is impl dep .
. when doing ptr conversions,
consider allignment req's;
the smallest types are the least restrictive
but if char.ptr -> int.ptr
you're not just saying
treat a char value as an int value
but asking for int address
in a place alligned only for char's .
. when making a mem alloc,
make sure the elment is the most restrictive
allignment you'll need
(ie, the largest type you expect to house
in that alloc block .)
3.30: news.addn/dev.mac/creating buttons on the fly?:
. c unions can be sharing a
common initial part u.union (p1.rec, ... .
4.2:
. all enum names used in a scope
should be unique,
so library enums should be names that include type
a const pointer is
type * const x
whereas pointer to rom is
const type *x
. structs not easily compared
not only because padding details are impl'-dep'
but also, unnamed fields (including padding)
are not init'd, so would contain random values .
4.4:
. c`linkage refers to how
declarations are bound to def's;
if the decl' is the def',
then say no linkage occurred .
. for c to fit in the
iso 646-1983 invariant code set
it needs to replace some of its ascii with trigraphs:
eg,
but function and extern names
are unique only to 6 char's
-- depending on the limits of
your system's assembler and linker .
. {short, int} are atleast 16bit,
and at most the size of long;
long is atleast 32bit .
2.28:
. for a (char to int).conversion to be portable,
specify whether the char is { signed, unsigned}
when storing non-char data there .
3.1: bk K&R`C:
. chars (bytes) are coerced in arithmetic expr's
so its important not to let them
slide into those without specifying
whether they are {signed, unsigned} .
3.4:
. the math functions expect both ( include math.h)
and a signature that states inout types;
then this relaxes need for
explicit casting of arg to double
for lib`math functions .
bit twiddling idioms:
. (~077 & x) sets last 6bits to zero
independent of int size .
-- esp'ly usefulness as
right-shifting negatives is not portable .
. to get what you expect,
you'd need to make it positive before the shift
and then redo the sign after .
sci:
. is it always true that a left shift is a mult?
[...: yes, by definition]
what is going on in big vs little endian?
. a portable way to get /n/ bits is
~(~0<<n)
-- useful for masking a bit field of size n .. if the arithmetic is 2's complement
then the right-most bit can be zeroed by:
(x) & (x-1) .
sci:
. useful to know for efficient bit counting ?
[2010.1.17: book of answers:
. count how many times you can do x`& (x-1)
before x becomes zero .
]
3.4: c`s conditional expression:
(truth)?(return for true): (return for false)
is a function
and c functions must have a static known return type,
so in the case of numbers,
the returns for both truth cases
must be in the same type class cluster;
eg, if the cases are {integer, float}
then the coercion rule`s advice to the compiler
is that this instance of the ?:-function
is returning float .
3.7: comma operator/2 uses:
. comma operator is used in macros
where a multi-step operation
has to be a single expression;
and, as a set notation,
for places that expect a stmt followed by (;)
those places can have (..., ..., ...;) .
. the c goto was primarily a
primitive exception system;
and for nested loops,
to break or continue deeper than current loop .
3.14:
. while (extern symbol) says find it elsewhere
(static symbol) says the symbol is local to file
meaning not bindable by an extern .
. all file-level symbols are ever-existing;
[existing atleast until main's termination?]-2010.1.17
having static locals (those local to a functions
or other blocks, rather than at file-level),
is a way to say ever-existing and local .
[this differs from my prev'understanding,
but seems obvious now]
. the scope of a file-level symbol
is from {def, decl} on downward;
[you might call that subfile scoping,
as it creates a subfile by not applying file-wide .]
. top-level symbols (both external and static),
must be init'd with a compiler-eval'able expr .
. register var's are like auto
in that they don't make sense being at top level .
. the reason static symbols are called such
is for involving non-dynamic (ie, static) allocation;
storage is created at compile time [or link time]-2010.1.16
and doesn't change after that .
. #undef does an un-#define
and is meant to be used along with a decl'
to insure that the declared symbol is
existing as a function
rather than as a macro .
. c typing for ptr is read like so:
for the example ( int *ptr: ),
* is a deref'operator;
and, derefing the ptr gets an int,
so ptr must be a pointer .
*p++ means *(p++)
-- right-to-left assoc' for all unaries .
. one reason c has string be null-terminated,
is to make quick work of substrings
[and it can be more space-efficient .]-2010.1.16
. another purpose of substring is to
index backwards, eg, ptr[-2] is possible
if the a function is handed
the address of the middle of an array .
. a string literal is translated to
a ptr to a static address
and so can be given to a function`arg
of type (char *p) or (char p[]) .
3.15:
. ptr arithmetic includes one beyond the end;
eg, for ar[size]
you can loop
while ptr++ < size
even though bounds are 0 ... size-1 .. sizeof(obj).size_t .
. type casting can treat a ptr to one type
as a ptr to another .
3.16: c`idiom for ptr:
. target string copy looks like equality test:
while(*p1++ = *p2++);
-- this says assign one char
then incr' both pointers for the next assign;
the assignment returns to the transfered value,
and during a c`string traverse,
there will eventually be a null char
indicating [end of str]
which the assignment functions to the while.loop
thereby terminating the loop
since a null char is interpreted as false .
. c stack idiom:
push(x): *stack++ = x .
pop(&x): x = *--stack .
3.19:
. to avoid complicated recursive type decl's,
build these structs in small steps
using the typedef operator .
. sizeof(type) also works as
sizeof var -- without paren's .
. within the unix command line,
the idea behind dashing param's
is that command is a function taking an arg,
whereas other optional param's can be thought of as
providing a diffn't function
where the -params are part of the function`name,
eg, cmd-p1-p2 (arg)
can be said in unix as:
cmd -p1 -p2 arg
. some lib'functions have a return type of (void *),
but that is really a generic:
when used, you're expected to type cast the call
showing what type of pointer you're assigning it to .
. use typedef to stay portable:
int, long, short
should be replaced with z8, z16, z32,
3.25:
. the default compile produces both the obj file (.o)
and an exe'able (named a.out
cc -c ... is how to make object files without an exe'able
cc -S ... will emit asm (.s) instead of obj modules
then separate compilation means
cc will handle any mix of {.c .s .o} files
. to produce an exe'able (.out)
one of the files needs to include main()
. to rename a.out use cc -o myrunname
. cc -p will make the profiler available;
after any exe'ing use (prof myexename)
to get a profile listing from the latest exe'ing .
3.27:
exit() is main's return stmt:
. the returning values of main()
-- or other c functions (esp'ly libraries) --
may be giving status .
. exit(x) is both flushing file`buffers
and returning x:
. a return of zero indicates operation was normal,
and then abnormals can be cased
and used as exception signals .
. in main which is always a proc,
(return x) is equ' to exit(x) .
. besides undef, another way to
redef a function that's impl'd as a macro
is to never reuse a library function's name,
so you have to know everything that's in
what you include;
but what about implied includes?
aren't there those?
. if inconvenient
do your code in macros that will wrap
uniquely identifying inconvenient names .
. stdio is for high-level inout,
fcntl is for low-level .
. mac#iphone encourages use of mysql db for data storage .
3.29: bk"c
. c`float-> int ? float is truncated .
c`integral promotion:
{char, short , bit-field, enum} -> int;
but for other not an int`subset ?
these discretes get promoted to unsigned int .
. number conversions can get tricky due to
impl-dep defs of subtypes
and whether your enum's fit in the impl's int .
. per impl,
work with types you know the size of .
. declare all types,
the default decl is int -- an impl-dep size .
. when not using a function`s param or return
do type it void .
. if not using an expression`s return,
do cast in void .
. make sure sizeof can get size of both
the ptr and its object
can get a (ptr -> int).conversion
but size of int for storing ptr value
is impl dep .
. when doing ptr conversions,
consider allignment req's;
the smallest types are the least restrictive
but if char.ptr -> int.ptr
you're not just saying
treat a char value as an int value
but asking for int address
in a place alligned only for char's .
. when making a mem alloc,
make sure the elment is the most restrictive
allignment you'll need
(ie, the largest type you expect to house
in that alloc block .)
3.30: news.addn/dev.mac/creating buttons on the fly?:
. create the button using4.1:
+alloc
-initWithFrame:,
and add it to your window's view hierarchy with
-addSubview:
....
Don't forget to delegate or nothing will happen!
Also, before doing this, you might want to read more about
NSResponder and NSView
. In addition, read about Cocoa's
memorymanagement and in particular NSAutoreleasePool
Next, it might be wise to check out
how you want your application to hierarchically
nest NSView (sub-)object in it's NSWindow's
. c unions can be sharing a
common initial part u.union (p1.rec, ... .
4.2:
. all enum names used in a scope
should be unique,
so library enums should be names that include type
a const pointer is
type * const x
whereas pointer to rom is
const type *x
. structs not easily compared
not only because padding details are impl'-dep'
but also, unnamed fields (including padding)
are not init'd, so would contain random values .
4.4:
. c`linkage refers to how
declarations are bound to def's;
if the decl' is the def',
then say no linkage occurred .
. for c to fit in the
iso 646-1983 invariant code set
it needs to replace some of its ascii with trigraphs:
eg,
??= -> #, and
??! -> |
.
. when extending a macro to next line with \
the preprocessor replaces that
and the following eoln with nothing
when the intuitive action would be
to replace it with a space .
if you need a space to separate tokens,
you need to add it yourself .
4.7:
. memcpy only works as expected if
arg's are not overlapping .
. if the args may be overlapping
then use memmov .
. realloc can lengthen your array
without changing the primary address .
. is it impl'd as a handle ?
or like a file, as strings of blocks? .
some things for math are in stdlib.h .
. for ctype.h,
the c stands for char;
it has to{upper, lower}
and the truth functions: { ispredicate(char) } .
4.8:
iPhone SDK Development
- Bill Dudney, Marcel Molina, Chris Adamson (Pub. The Pragmatic Bookshelf)
and iPhone in Action
- Christopher Allen, Shannon Appelcline (Pub. Manning),
. stanford`iphone 101 xcode/help/doc's
. when extending a macro to next line with \
the preprocessor replaces that
and the following eoln with nothing
when the intuitive action would be
to replace it with a space .
if you need a space to separate tokens,
you need to add it yourself .
4.7:
. memcpy only works as expected if
arg's are not overlapping .
. if the args may be overlapping
then use memmov .
. realloc can lengthen your array
without changing the primary address .
. is it impl'd as a handle ?
or like a file, as strings of blocks? .
some things for math are in stdlib.h .
. for ctype.h,
the c stands for char;
it has to{upper, lower}
and the truth functions: { ispredicate(char) } .
4.8:
iPhone SDK Development
- Bill Dudney, Marcel Molina, Chris Adamson (Pub. The Pragmatic Bookshelf)
and iPhone in Action
- Christopher Allen, Shannon Appelcline (Pub. Manning),
. stanford`iphone 101 xcode/help/doc's
-- see the class header files .
4.8:
. signal.h gives c a form of
exception handling:
any place in your subprogrms can define
new exception handlers
that can print to err log
where the err happened .
. if your mem alloc program is violated,
it can raise(sigsegv) -- segment violation
. if a function is passed bad arg's
it can raise(sigill) -- illegal function image
. sigterm needs a handler that
dealloc's dynamic mem .
sci:
. not clear how signals work ?
need web search
. can your handler avoid termination by
defining handlers,
or is your handler saying
what should happen before termination?
. does your handler need the exit stmt
after the cleanup routine?
bk"steele` c/signals:
. the usual is for the handler to
return at the point the interupt occured
but it can also call exit or longjmp .
. traditional c also has 15 software signals
(to impl exceptions like ada)
but ansi c requires only hardware signals .
. traditional c has consider ed longjmp to be more
portable than signals as an exception mech .
. if any of your severs use longjmp
here is how to use them:
-- include setjmp.h --
jmp_buf env;
void try()
{
int err = setjmp(env);
if (err), exceptionhandler;
servercall;
}
--. if server does a longjump
then it recalls the set jmp
and redefines err to non-zero (true) .
. per signal, and per platform,
you need to test whether interrupts abort
or don't return after handler
to the place of interupt .
. this may be why its best to use setjmp
and then have all handlers do a longjmp??
. the simplest and safest is to
set the handlers for all signals to
save prgm space and advise user to reopen prgm;
the prgm then looks over the log
to see what may have caused the err,
and can ask usr to email report .
. if a subroutine raised() the exception
then if the handler doesn't do
an exit or longjmp,
then execution goes back to
the code that called raise()
. this might be useful for
setting an external param block correctly .
. to set your own signals
see what's already defined in signal.h
and then define an unused value .
. the signal function returns a
pointer to the current handler,
so that when your done activating your handler,
you can restore the old handler .
. the c exception system allows for
doing exceptions the way Ada does it:
. assume level 1 can handle it,
if level 2 wants to handle it,
then it can do that by replacing level 1`s;
if it wants to cooperate with level 1,
it would finish its handler by restoring level 1`s handler,
and then reraising the exception .
. portability is less of a concern when
staying away from c`s conveniences,
and instead reimplementing them in OOPish ways
that automate the correct usage of
more basic features .
. string array may differ from
ptr to string literal
because the literal for the ptr
is implicitely a constant
whereas the literal for char array
is an assignment to a variable .
. since the external names are so short,
defines can give them normal-sized names .
. another use of the pre`processor
can be setting the defines to ones that
don't clash with others in the current system .
can lint help here?:
. c will let you goto from outside a block
to the middle of the block,
and you might unintentionally do this
by a spelling mistake
goto'ing to the wrong label .
. c will let you extern locals,
but the effect of this is impl'dep,
and it might be done accidently .
. I would think extern would be a
reasonable way to say that
a global was being used,
but in c, it says that your extern'd local
is going to be from some global
to be found in one of the files
you had linked together during the compilation .
4.15:
. the string literal's effect
depends on the type it's being assigned to:
array with unspecified length
(same ptr to char)
gets the literal plus a null;
array length is specified?
then string literal is assigned
and for any remaining chars
null is assigned .
4.16:
. c won't just drop your macro param in a string,
you have to do this in the macro body:
".." #param ".."
. the complexity is that
c strings are not nestable
while macro param's can be string literals
so when the #param is in the body,
param is altered to be seen in string as is:
if the param contains chars like " or \
then they are escaped, eg, given:
macro(p) #p;
then:
macro(\) --> "\\" .
. given:
m(p) "[" p "]",
then:
m(\) --> "[\\]" .
. the ##-operator concat's tokens:
. given m(a,b) a##b
m(c,1) --> c1 .
. includes where the file is quoted
vs include with angle brackets around file.h
can include the pathname:
include "dir/file"
so you can pull components from various lib's .
. if your include's don't mention a pathname
then the effect could be impl-dep .
. the reason impl's differ is
some like the idea of being OOPish
and over-riding a lib`s sublib,
in those impl's,
a lib could support that by
not specifying the pathname of its sublib .
. it depends on whether they
( do an include and then
rescan for nested includes
)
vs, doing a recursive include,
where the lib`s folder is the current folder
and the sublib includes are done while there,
then that temp file
is used for when the client asks to include the lib .
)
. if instead
the current folder is the client`s
the whole time,
then the sublib include,
when having no pathname,
could use the client`s sublib,
rather than the lib`s sublib .
. beware deciding to keep things portable by
using pathnames
only to accept later the reuse of
other people`s lib's
without first checking their code
for the use of pathnames .
. the purpose of the angle-brackets syntax
for includes
is to indicate that the compiler system
knows where to find the expected lib,
and will know the pathname .
. the ( #if x ).syntax expects x to be a num
-- less versatile than c`s if .
. in unix, c #define's can also be declared
on the command line as a parameter of cc :
cc -PARAM=/some val/ m.out
. and to have a default for this param, use:
#ifndef PARAM
#define PARAM = /default/
#endif
. the ideas of not eval'ing param's
is important to sideaffects
as from the user`s code
you expect the param to be eval'd only once
(or none at all if quoted)
but in a macro
it's eval'd for as many times as
referenced by the macro body .
. macro's serve as generics
since no type checking on params is done .
4.18:
. c's #if can take complex truth expr's,
eg:
#if defined(a) && a ...
.
. just as print stmt's can debug during run-time,
the #error is a print stmt for compile time:
#error __FILE__ __LINE__ [error msg].string
4.18: obj'c:
. in c format strings,
similar to the way "%d" means a
decimal object`s string value,
so too an OOP object's string value
is expressed as "%@"
and the way you define
your class`s image or string value
is by overriding this:
- (NSString *)description; .
. mac's ns lib has both a mutable and const form
for {string, array, dict, set}
nsArray can be filled with any-size list,
and like c`string it's terminated with a sentinel,
in this case, nil .
4.19: mvc (model-view-controller) pattern
. with the mvc pattern,
your portable app stays in the model domain,
and then the view
is the gui toolkit provided by a platform
so most of your platform-specific code
then resides in the controller .
. a controller`s outlets
are its bindings to both your model and the view .
. a controller`s actions
are sockets accepting msg's from the view .
"(the view actions
point back to your controller)
. the view is represented by xib.files,
xml-based nib files
(nib: nextstep interface builder) .
. ib is helping you lay out ui widgets,
and create controllers to connect to it .
(controllers can also be created in xcode) .
. on app`startup,
the nib is loaded to define a view,
and to fill the view with model`values,
a msg"[awake from nib] is sent to
any controllers connected with that view .
. this msg is available because
your controller was subclassing ns`object;
in some situations you want to
first use the superclass`s method,
and then run your own method,
but in the case of [awake from nib],
the msg is abstract, empty,
and thus a call first to super
would have no effect .
touchup(inside) =
click (mousedown and mouseup within control)
touchup(outside) =
click but dragged so mouseup happens outside of control
-- the term "(touch) is specific to
the iphone or inspired by it .
. when event occurs, action is invoked on target object
. we see a button push results in activating
[UI control event touch up inside].event
which because of view-controller connections
will send a msg from button to the controller
. if it's like a slider,
it's creating a value that the
controller needs to know about,
so then the msg`param's include an
obj.pointer to the slider:
eg,
polygon`[adjust number of sides]( slider.id ).proc
. this msg is called an action method
because the view`s action depends on
what controller it's hooked up with,
. if it's a really complicated response to
multi-touches,
you may want a pointer to the [ui event] as well .
multiple-target actions are specific to iphone:
. for iphone, [interface builder] supports
connecting a widget modification to several controllers,
so that iphone`ui kit will then send msg's to
multiple controllers .
. nib's are neat because
[interface builder] helps you produce them by gui;
--.
and if you can transform the xml
to something readable
you might be able to programmatically
change nib files rather than
programmatically change the view directly .
. a nib file is the same idea as html;
you can see the document`s data structure directly
rather than having to imagine how a script`s execution
unfolds into a document .
. there is some way to ask ib [interface builder]
to generate obj'c code into {.h, .m} files
rather than xml in the nib .
. however,
it doesn't make template code of everything:
"(if I have a slider msg
being sent to the controller,
that code won't be generated;
it happens behind the scene
)
. the problem is that ib is not actually
generating code [see next]
. this could imply that changing the nib file
would have no effect
until the system got msg that
frozen things had to be updated also?
. ib simply creates the xml
as a modular way of communicating with the compiler .
. if that is the case,
then one way to dynamic views,
is to change a module`s nib,
then recompile that module
which then re-considers the nib,
then relink the module to the program .
--
. the stanford audience kept picking apple`team apart
for making this ib guy front and center;
I thought it would all make sense to them
if they had read the doc's that explained
apple sells a pkg specifically designed to
ease the creation of dynamic gui's,
one's whose build depends on
the current inputs from user or other environs .
to make a target-action connection .
. the code is providing the same info
ib would use:
. the api and [ui control events].bitmask
are found in [ui control].h .
@interface [ui control]
[{add, remove} target : action : for control events]
( target.id
, action.SEL
, [control events].[ui control events]
).member`proc
@end
. you can see ib calling [add target action]
when you make the connection
from widget
to controller`msg,
and then the app window shows
an extra connection entry .
. likewise,
instead of using the app window
to remove a connection,
you could have instead called
[remove target action]
. to use ib,
notice in your xcode project window,
a resources.folder
where you can click-open some xib.file;
it will then contain
(when set to icon view),
icons like a white sheet of paper
that opens to be your gui view
(ie, a pasteboard for widgets)
. there will be gold cubes for the app,
and the controller .
. opening the app will show you
a list of view-controller connections
so you can remove some to redo them .
. in order to get help creating connections,
open the [white sheet].icon from the gui
and drag-click from a widget
to the [gold cube -- title"controller].icon
. it will then raise a controller`context.menu
showing msg's you can connect to
(in the example, he connects the
[decrease to controller`decrease].button)
. this controller menu was available because
"(your header defines the outlets and the actions)
. a controller`s outlets are its bindings to
both your model and the view .
(outlets define all ref's to ib`obj's)
. a controller`s actions are
sockets accepting msg's from the view .
"(ib actions define
all the methods that can be called on events)
"(the view actions
point back to your controller) .
. the reason for including the colons
in the function name
is that you can refer to the function name
as a value,
so then instead of calling a literal function name,
you could first choose the function you want to call
keeping that in myact,
and then call the function by calling myact:
myobj`(myact)
. modern languages allow overloading of functions,
so that a -(x) is a diff'nt function
than -(x,y) .
obj'c would let you distinguish these literals like so:
[-:] vs [-::],
here is some obj'c code:
SEL myact = @selector(minusMinuend:subtrahend) .
. the .m in place of .c, stands for 'iMplementation .
[2010.1.16: or Machinery, Mechanism]
. to have your new class def
inherit from [ns`object];
ie,
@interface myclass : NSObject,
you need to #import the header
Foundation/Foundation.h
. the syntax for header is:
@interface myclass: superclass
{block if instance vars}
- member msg
+ class msg
@end
. now you can use your myclass header
in a .m file:
@implementation myclass
. it needs to import your header file:
#import "myclass.h"
. your impl gets at the instance var's with
[self var]
. the syntax for impl' is:
@implementation myclass
- msg`signature {block}
...
@end
. you can write mostly in c code,
except when you want something from the os
that wants obj's (tagged structs) .
. a favorite thing to impl is init,
like so:
- init.id`=
{ self`= super`init ?
[do your init]; return self
}
--. you're letting super call its init first
and if it comes up with something non-nil,
you are adding to the init process;
. the way to use it is:
obj`= [[myclass alloc] init]
-- which doesn't seem to make sense,
except that compilers are smart,
and know what we really want;
with only a simple compiler,
we'd be providing mem (a self) for our init,
when our init was just going to turn around
and toss that mem in favor of
getting some mem that was init'd by super .
. but why would I assume (self`= super`init )
is a pointer transfer?!
self is allocated, and the assignment is really
an implicit self/`= super`init
-- like ada`s self.all := super.init .
conversely, dealloc calls super
in the reverse order that alloc did:
- dealloc.proc`= { [your cleanup]; super`dealloc }
--. this is what the system calls
before closing a stack alloc .
. if the client wants to dealloc something it declared,
it reverses an alloc or copy with (release);
then the system will call your obj`dealloc,
which is there to give object
a chance to (release) any inputs
it has previously (retain)'d .
. if a client did not itself declare the object,
but wants to share, then it would call (retain)
and when it was done wanting to share,
it calls (release) .
. generally, these are part of the ref'counting
system:
retain -- incr's the count
release -- decr's the count .
. if you are done with your share of it,
the safe thing to do is
not only call release to match a retain,
but also set it to nil
(it nil's your pointer, not the obj),
so that if you send it a msg,
then the result is null .
person`setname( newname/.#.char ):
self`name = newname ?
--. then assignment is already done .
no?
--. self`name can be released,
and since this param"newname belongs to
someone else, (being it's a gift from a param!)
we need to increase the gift`s ref'count
with retain: .--
self`name`release;
self`name`= newname`retain .
--. ofcourse all this is nicely moot if using
@interface/@properties
and @impl'/@synthesize;
then, that exact code is written for you .
. conversely, if you are providing an obj'
to a param by returning an obj,
then you need some way of giving the caller
a chance to use your return
and then release your obj' later;
but since you are a function,
you are getting dealloc'd as soon as you make the return!
the obj'c solution
is to have you call autorease(return):
fullname.string`=
"(
result/.string`= str`alloc;
result`autorelease;
return result
) .
. when you ask for threading,
part of thread mgt duties
is asking for an autorelease pool
to impl' the autorelease feature
that is provided to functions that return new obj's .
. the xcode template code gives you
one thread and one pool to go with it .
@property gets its name from
the classic oop convention
that accessable things are called
properties of the object
--. copy can be your assurance to clients
that you are giving them a copy
and can modify what you are both sharing;
or, it means
that anything assigned to this obj
will be copied to insure that
no sharing is taking place .
. when using @synthesize,
you can use that as a rename:
@synth' [name the client uses] = [my internal name] .
. when ivar's (instance var's) are
used from within your own methods,
you can refer to them as their instance name,
in which case the property`constraints
are no longer valid;
eg, copies are not just copies .
so, to make the constraint apply,
use self.[property name] .
. also you can have a setter
that does a lot more than assignment,
so again
name`=
vs self.name`=
becomes crucial .
person`setage(newage).proc`=
"( self.age`= newage)
--.infinite loop by recursion!
because the dot notation
calls the setter -- self`setage(newage)
-- which is what we're trying to impl!
4.22:
NULL = (void *)0
4.23:
. see stddef.h;
(void *) is the generic ptr .
. it's assignment compatable with anything and vice versa,
. this is the type malloc returns
in order to give a generic object to a particular type .
. function and array id's are const'pointers
so they can be assigned as such
(with the address operator);
but a subscripted array is a deref'd pointer,
eg, ptr = &array[n] .
sci:
. no mention of taking the address of a struct`s component;
recall that was not allowed in pascal .
. it's an error if a struct's init is
larger than the struct;
(presumably the compiler will report errors)
but not an error
when string init leaves no room for null sentinel;
ie, the sentinel addition method is
to initialize char arrays with nulls
wherever the init is short on chars:
. there is no forcing you to
null-terminate your char arrays,
although all the char lib routines depend on that .
sci:
. be sure to check where
every function is defined;
I was surprised the teacher used malloc as
an example of function declares;
because isn't that part of some lib you include?
perhaps he meant this:
. when including a .h file to
declare a lib`s functions,
make sure you have the right .h file,
and that you're spelling the function correctly .
. if you messed up either way,
then the declare is done /implicitly/,
in which case the
default return type is /int/,
whereas if you were using malloc,
declaring that to be int
would work only sometimes
since pointers do not always fit in an int .
iphone terms:
. kvo (key-value observing) and notifications
are how {model, controller} communicate,
vs the {view, controller} doing it through
target-action, and delegation .
iphone ideas:
. ui.kit(on the iphone only
but cocoa has a similar lib')
includes ui.view.controller
which is a generic controller to subclass .
. controllers are composable,
so their code can be shared .
4.23:
. the limits of ints are in limits.h,
while those of floats are in floats.h:
. within the float limits there are often limits for each of
[ FLT -- float
, DBL -- double
, LDBL -- long double]
FLT_ROUNDS = rounding towards where?
( zero: 0
, nearest: 1
, +inf: 2
, -inf: 3
, others: impl'dep
) .
. when you a see a * in the following,
it refers to above type symbols
{ FLT , DBL , LDBL, FLT_ROUNDS }:
*_EPSION -- steps between discrete values
(smallest for x+1.0 /= x)
*_MIN -- smllest available fraction
= 10**MIN_10_EXP
*_MAX -- largest available number
= 10**MAX_10_EXP
FLT_RADIX = {2(bits), 8(bytes), or 10(bcd)}
-- the base around which float limits are defined .
*_DIG
-- #[available fraction digits] .
*_MANT_DIG
-- #[digits in mantissa of sci'notation using base FLT_RADIX]
*_{MIN,MAX}_EXP
-- exponent to the base FLT_RADIX of
smallest fraction or largest number;
eg for 32bit and 64bit in base 2: -125, 128; -1021, 1024 .
*_{MIN,MAX}_10_EXP
-- exponent to the base 10 of smallest fraction or largest number .
. unsigned does modulo math
(doesn't overflow with warning;
instead, it's wrapping around range)
. if you mix unsigned with signed,
the natural reaction is to coerce to signed,
but c's implicit coercion does the opposite:
(unsigned > -1) is false in c !
. you'll need to explicitly convert:
((signed)unsigned > -1) is true .
. the reason c does that
is that the use of unsigned is specialized to do
modulo math
so mixing negatives would happen only in the
rare case of
using unsigned to save a bit of space
or when you were using that elegant c idiom
where
-1 can always stand for the largest unsigned value
of any range size (byte, word, long) .
. depending on the implementation,
c's char may be any of
{ signed,
, unsigned
, signed restricted to range non-neg'
} .
. to see your impl's style, check for:
char c = -1;
int i = c;
print i; ->
{ -1 --. char is signed .
, 255 --. is unsigned .
, err --. is signed with range non-neg' .
} .
. what shows when you negate a signed char?
besides testing for sizes
you can depend on limits.h .
4.24:
. (void *) is a generic ptr
but pointing only to obj's not functions;
all pointers to function
must be declared as being a certain signature
(a declaration of param' and return types) .
. while (void *) can be declared,
(void *)[] cannot .
4.25:
extern T array[]
--. this is a declaration;
the definition that matches it
must give a range along with an init
or the init must implicitely define the range .
. page#113 has some bizarre predictions about
multi-dimension arrays;
eg, (*(a+1)+2) should still be for &a[1][2]
as if *(a+1) can get an element of the array
but only if it's not followed by
more pointer-legal arithmetic
in which case it acts as if
multi-dim arrays are impl'd as
array of pointer to array .
. it does follow from the definition of
array subscription:
a[i][j] = *(*(a+i)+j)
. what makes it confusing is the
convenience factor:
it has rules that follow no particular model,
choosing instead to
reduce the amount of programmer writing .
. when enum's are intro'd into a scope
(by giving a var an enum.type )
no new symbols can take the names of
any of the enum`s literals .
4.26: sci.addn/dev.c/apple`s use of it:
. here they used !(s) not !s :
#if !(defined(KLD) && defined(__STATIC__))
4.27:
. pointers can refer to struct internals
except bit fields .
. pointers in rec's are like in arrays;
so, p1 > p2 if
field p2 is at a field declared later than
field p1 .
syntax within struce:
unsigned field : fieldsize;
. if no name then the field is for padding;
if no name and fieldsize = 0
then padding is sized for word completion,
ie, for making the next field be word-alligned .
. there are some drawbacks to bit fields:
they can't cross word boundaries,
so to be space-efficient
they may depend on the platform`s wordsize .
eg, 3bit * 3 fit into 16 but not 8 bit words .
the authors weren't convincing? web:
4.8:
. signal.h gives c a form of
exception handling:
any place in your subprogrms can define
new exception handlers
that can print to err log
where the err happened .
. if your mem alloc program is violated,
it can raise(sigsegv) -- segment violation
. if a function is passed bad arg's
it can raise(sigill) -- illegal function image
. sigterm needs a handler that
dealloc's dynamic mem .
sci:
. not clear how signals work ?
need web search
. can your handler avoid termination by
defining handlers,
or is your handler saying
what should happen before termination?
. does your handler need the exit stmt
after the cleanup routine?
bk"steele` c/signals:
. the usual is for the handler to
return at the point the interupt occured
but it can also call exit or longjmp .
. traditional c also has 15 software signals
(to impl exceptions like ada)
but ansi c requires only hardware signals .
. traditional c has consider ed longjmp to be more
portable than signals as an exception mech .
. if any of your severs use longjmp
here is how to use them:
-- include setjmp.h --
jmp_buf env;
void try()
{
int err = setjmp(env);
if (err), exceptionhandler;
servercall;
}
--. if server does a longjump
then it recalls the set jmp
and redefines err to non-zero (true) .
. per signal, and per platform,
you need to test whether interrupts abort
or don't return after handler
to the place of interupt .
. this may be why its best to use setjmp
and then have all handlers do a longjmp??
. the simplest and safest is to
set the handlers for all signals to
save prgm space and advise user to reopen prgm;
the prgm then looks over the log
to see what may have caused the err,
and can ask usr to email report .
. if a subroutine raised() the exception
then if the handler doesn't do
an exit or longjmp,
then execution goes back to
the code that called raise()
. this might be useful for
setting an external param block correctly .
. to set your own signals
see what's already defined in signal.h
and then define an unused value .
. the signal function returns a
pointer to the current handler,
so that when your done activating your handler,
you can restore the old handler .
. the c exception system allows for
doing exceptions the way Ada does it:
. assume level 1 can handle it,
if level 2 wants to handle it,
then it can do that by replacing level 1`s;
if it wants to cooperate with level 1,
it would finish its handler by restoring level 1`s handler,
and then reraising the exception .
. portability is less of a concern when
staying away from c`s conveniences,
and instead reimplementing them in OOPish ways
that automate the correct usage of
more basic features .
. string array may differ from
ptr to string literal
because the literal for the ptr
is implicitely a constant
whereas the literal for char array
is an assignment to a variable .
. since the external names are so short,
defines can give them normal-sized names .
. another use of the pre`processor
can be setting the defines to ones that
don't clash with others in the current system .
can lint help here?:
. c will let you goto from outside a block
to the middle of the block,
and you might unintentionally do this
by a spelling mistake
goto'ing to the wrong label .
. c will let you extern locals,
but the effect of this is impl'dep,
and it might be done accidently .
. I would think extern would be a
reasonable way to say that
a global was being used,
but in c, it says that your extern'd local
is going to be from some global
to be found in one of the files
you had linked together during the compilation .
4.15:
. the string literal's effect
depends on the type it's being assigned to:
array with unspecified length
(same ptr to char)
gets the literal plus a null;
array length is specified?
then string literal is assigned
and for any remaining chars
null is assigned .
4.16:
. c won't just drop your macro param in a string,
you have to do this in the macro body:
".." #param ".."
. the complexity is that
c strings are not nestable
while macro param's can be string literals
so when the #param is in the body,
param is altered to be seen in string as is:
if the param contains chars like " or \
then they are escaped, eg, given:
macro(p) #p;
then:
macro(\) --> "\\" .
. given:
m(p) "[" p "]",
then:
m(\) --> "[\\]" .
. the ##-operator concat's tokens:
. given m(a,b) a##b
m(c,1) --> c1 .
. includes where the file is quoted
vs include with angle brackets around file.h
can include the pathname:
include "dir/file"
so you can pull components from various lib's .
. if your include's don't mention a pathname
then the effect could be impl-dep .
. the reason impl's differ is
some like the idea of being OOPish
and over-riding a lib`s sublib,
in those impl's,
a lib could support that by
not specifying the pathname of its sublib .
. it depends on whether they
( do an include and then
rescan for nested includes
)
vs, doing a recursive include,
where the lib`s folder is the current folder
and the sublib includes are done while there,
then that temp file
is used for when the client asks to include the lib .
)
. if instead
the current folder is the client`s
the whole time,
then the sublib include,
when having no pathname,
could use the client`s sublib,
rather than the lib`s sublib .
. beware deciding to keep things portable by
using pathnames
only to accept later the reuse of
other people`s lib's
without first checking their code
for the use of pathnames .
. the purpose of the angle-brackets syntax
for includes
is to indicate that the compiler system
knows where to find the expected lib,
and will know the pathname .
. the ( #if x ).syntax expects x to be a num
-- less versatile than c`s if .
. in unix, c #define's can also be declared
on the command line as a parameter of cc :
cc -PARAM=/some val/ m.out
. and to have a default for this param, use:
#ifndef PARAM
#define PARAM = /default/
#endif
. the ideas of not eval'ing param's
is important to sideaffects
as from the user`s code
you expect the param to be eval'd only once
(or none at all if quoted)
but in a macro
it's eval'd for as many times as
referenced by the macro body .
. macro's serve as generics
since no type checking on params is done .
4.18:
. c's #if can take complex truth expr's,
eg:
#if defined(a) && a ...
.
. just as print stmt's can debug during run-time,
the #error is a print stmt for compile time:
#error __FILE__ __LINE__ [error msg].string
4.18: obj'c:
. in c format strings,
similar to the way "%d" means a
decimal object`s string value,
so too an OOP object's string value
is expressed as "%@"
and the way you define
your class`s image or string value
is by overriding this:
- (NSString *)description; .
. mac's ns lib has both a mutable and const form
for {string, array, dict, set}
nsArray can be filled with any-size list,
and like c`string it's terminated with a sentinel,
in this case, nil .
4.19: mvc (model-view-controller) pattern
. with the mvc pattern,
your portable app stays in the model domain,
and then the view
is the gui toolkit provided by a platform
so most of your platform-specific code
then resides in the controller .
. a controller`s outlets
are its bindings to both your model and the view .
. a controller`s actions
are sockets accepting msg's from the view .
"(the view actions
point back to your controller)
. the view is represented by xib.files,
xml-based nib files
(nib: nextstep interface builder) .
. ib is helping you lay out ui widgets,
and create controllers to connect to it .
(controllers can also be created in xcode) .
. on app`startup,
the nib is loaded to define a view,
and to fill the view with model`values,
a msg"[awake from nib] is sent to
any controllers connected with that view .
. this msg is available because
your controller was subclassing ns`object;
in some situations you want to
first use the superclass`s method,
and then run your own method,
but in the case of [awake from nib],
the msg is abstract, empty,
and thus a call first to super
would have no effect .
touchup(inside) =
click (mousedown and mouseup within control)
touchup(outside) =
click but dragged so mouseup happens outside of control
-- the term "(touch) is specific to
the iphone or inspired by it .
. when event occurs, action is invoked on target object
. we see a button push results in activating
[UI control event touch up inside].event
which because of view-controller connections
will send a msg from button to the controller
. if it's like a slider,
it's creating a value that the
controller needs to know about,
so then the msg`param's include an
obj.pointer to the slider:
eg,
polygon`[adjust number of sides]( slider.id ).proc
. this msg is called an action method
because the view`s action depends on
what controller it's hooked up with,
. if it's a really complicated response to
multi-touches,
you may want a pointer to the [ui event] as well .
multiple-target actions are specific to iphone:
. for iphone, [interface builder] supports
connecting a widget modification to several controllers,
so that iphone`ui kit will then send msg's to
multiple controllers .
. nib's are neat because
[interface builder] helps you produce them by gui;
--.
and if you can transform the xml
to something readable
you might be able to programmatically
change nib files rather than
programmatically change the view directly .
. a nib file is the same idea as html;
you can see the document`s data structure directly
rather than having to imagine how a script`s execution
unfolds into a document .
. there is some way to ask ib [interface builder]
to generate obj'c code into {.h, .m} files
rather than xml in the nib .
. however,
it doesn't make template code of everything:
"(if I have a slider msg
being sent to the controller,
that code won't be generated;
it happens behind the scene
)
. the problem is that ib is not actually
generating code [see next]
. this could imply that changing the nib file
would have no effect
until the system got msg that
frozen things had to be updated also?
. ib simply creates the xml
as a modular way of communicating with the compiler .
. if that is the case,
then one way to dynamic views,
is to change a module`s nib,
then recompile that module
which then re-considers the nib,
then relink the module to the program .
--
. the stanford audience kept picking apple`team apart
for making this ib guy front and center;
I thought it would all make sense to them
if they had read the doc's that explained
apple sells a pkg specifically designed to
ease the creation of dynamic gui's,
one's whose build depends on
the current inputs from user or other environs .
. ib is not actually generating code;. next is a manual (codified) way
it's instantiating obj's like a ui`button,
and then archiving it
to be unfrozen when your program starts up;
so it's not creating a new instance .
. remember,
"(add target with action ...
(for control`events?))?
it's actually calling that method:
[add target action for control events]
to make a target-action connection .
. the code is providing the same info
ib would use:
. the api and [ui control events].bitmask
are found in [ui control].h .
@interface [ui control]
[{add, remove} target : action : for control events]
( target.id
, action.SEL
, [control events].[ui control events]
).member`proc
@end
. you can see ib calling [add target action]
when you make the connection
from widget
to controller`msg,
and then the app window shows
an extra connection entry .
. likewise,
instead of using the app window
to remove a connection,
you could have instead called
[remove target action]
. to use ib,
notice in your xcode project window,
a resources.folder
where you can click-open some xib.file;
it will then contain
(when set to icon view),
icons like a white sheet of paper
that opens to be your gui view
(ie, a pasteboard for widgets)
. there will be gold cubes for the app,
and the controller .
. opening the app will show you
a list of view-controller connections
so you can remove some to redo them .
. in order to get help creating connections,
open the [white sheet].icon from the gui
and drag-click from a widget
to the [gold cube -- title"controller].icon
. it will then raise a controller`context.menu
showing msg's you can connect to
(in the example, he connects the
[decrease to controller`decrease].button)
. this controller menu was available because
"(your header defines the outlets and the actions)
. a controller`s outlets are its bindings to
both your model and the view .
(outlets define all ref's to ib`obj's)
. a controller`s actions are
sockets accepting msg's from the view .
"(ib actions define
all the methods that can be called on events)
"(the view actions
point back to your controller) .
. the reason for including the colons
in the function name
is that you can refer to the function name
as a value,
so then instead of calling a literal function name,
you could first choose the function you want to call
keeping that in myact,
and then call the function by calling myact:
myobj`(myact)
. modern languages allow overloading of functions,
so that a -(x) is a diff'nt function
than -(x,y) .
obj'c would let you distinguish these literals like so:
[-:] vs [-::],
here is some obj'c code:
SEL myact = @selector(minusMinuend:subtrahend) .
. the .m in place of .c, stands for 'iMplementation .
[2010.1.16: or Machinery, Mechanism]
. to have your new class def
inherit from [ns`object];
ie,
@interface myclass : NSObject,
you need to #import the header
Foundation/Foundation.h
. the syntax for header is:
@interface myclass: superclass
{block if instance vars}
- member msg
+ class msg
@end
. now you can use your myclass header
in a .m file:
@implementation myclass
. it needs to import your header file:
#import "myclass.h"
. your impl gets at the instance var's with
[self var]
. the syntax for impl' is:
@implementation myclass
- msg`signature {block}
...
@end
. you can write mostly in c code,
except when you want something from the os
that wants obj's (tagged structs) .
. a favorite thing to impl is init,
like so:
- init.id`=
{ self`= super`init ?
[do your init]; return self
}
--. you're letting super call its init first
and if it comes up with something non-nil,
you are adding to the init process;
. the way to use it is:
obj`= [[myclass alloc] init]
-- which doesn't seem to make sense,
except that compilers are smart,
and know what we really want;
with only a simple compiler,
we'd be providing mem (a self) for our init,
when our init was just going to turn around
and toss that mem in favor of
getting some mem that was init'd by super .
. but why would I assume (self`= super`init )
is a pointer transfer?!
self is allocated, and the assignment is really
an implicit self/`= super`init
-- like ada`s self.all := super.init .
conversely, dealloc calls super
in the reverse order that alloc did:
- dealloc.proc`= { [your cleanup]; super`dealloc }
--. this is what the system calls
before closing a stack alloc .
. if the client wants to dealloc something it declared,
it reverses an alloc or copy with (release);
then the system will call your obj`dealloc,
which is there to give object
a chance to (release) any inputs
it has previously (retain)'d .
. if a client did not itself declare the object,
but wants to share, then it would call (retain)
and when it was done wanting to share,
it calls (release) .
. generally, these are part of the ref'counting
system:
retain -- incr's the count
release -- decr's the count .
. if you are done with your share of it,
the safe thing to do is
not only call release to match a retain,
but also set it to nil
(it nil's your pointer, not the obj),
so that if you send it a msg,
then the result is null .
person`setname( newname/.#.char ):
self`name = newname ?
--. then assignment is already done .
no?
--. self`name can be released,
and since this param"newname belongs to
someone else, (being it's a gift from a param!)
we need to increase the gift`s ref'count
with retain: .--
self`name`release;
self`name`= newname`retain .
--. ofcourse all this is nicely moot if using
@interface/@properties
and @impl'/@synthesize;
then, that exact code is written for you .
. conversely, if you are providing an obj'
to a param by returning an obj,
then you need some way of giving the caller
a chance to use your return
and then release your obj' later;
but since you are a function,
you are getting dealloc'd as soon as you make the return!
the obj'c solution
is to have you call autorease(return):
fullname.string`=
"(
result/.string`= str`alloc;
result`autorelease;
return result
) .
. when you ask for threading,
part of thread mgt duties
is asking for an autorelease pool
to impl' the autorelease feature
that is provided to functions that return new obj's .
. the xcode template code gives you
one thread and one pool to go with it .
@property gets its name from
the classic oop convention
that accessable things are called
properties of the object
@property (readonly) <type> <name>;
@property (assign) <class/> <passes a pointer without calling retain -- dangling possible >
@property (retain) <class/> <shares an obj>
@property <copy> <class/> <provides a copy --not shared>
--. copy can be your assurance to clients
that you are giving them a copy
and can modify what you are both sharing;
or, it means
that anything assigned to this obj
will be copied to insure that
no sharing is taking place .
. when using @synthesize,
you can use that as a rename:
@synth' [name the client uses] = [my internal name] .
. when ivar's (instance var's) are
used from within your own methods,
you can refer to them as their instance name,
in which case the property`constraints
are no longer valid;
eg, copies are not just copies .
so, to make the constraint apply,
use self.[property name] .
. also you can have a setter
that does a lot more than assignment,
so again
name`=
vs self.name`=
becomes crucial .
person`setage(newage).proc`=
"( self.age`= newage)
--.infinite loop by recursion!
because the dot notation
calls the setter -- self`setage(newage)
-- which is what we're trying to impl!
4.22:
NULL = (void *)0
4.23:
. see stddef.h;
(void *) is the generic ptr .
. it's assignment compatable with anything and vice versa,
. this is the type malloc returns
in order to give a generic object to a particular type .
. function and array id's are const'pointers
so they can be assigned as such
(with the address operator);
but a subscripted array is a deref'd pointer,
eg, ptr = &array[n] .
sci:
. no mention of taking the address of a struct`s component;
recall that was not allowed in pascal .
. it's an error if a struct's init is
larger than the struct;
(presumably the compiler will report errors)
but not an error
when string init leaves no room for null sentinel;
ie, the sentinel addition method is
to initialize char arrays with nulls
wherever the init is short on chars:
. there is no forcing you to
null-terminate your char arrays,
although all the char lib routines depend on that .
sci:
. be sure to check where
every function is defined;
I was surprised the teacher used malloc as
an example of function declares;
because isn't that part of some lib you include?
perhaps he meant this:
. when including a .h file to
declare a lib`s functions,
make sure you have the right .h file,
and that you're spelling the function correctly .
. if you messed up either way,
then the declare is done /implicitly/,
in which case the
default return type is /int/,
whereas if you were using malloc,
declaring that to be int
would work only sometimes
since pointers do not always fit in an int .
iphone terms:
. kvo (key-value observing) and notifications
are how {model, controller} communicate,
vs the {view, controller} doing it through
target-action, and delegation .
iphone ideas:
. ui.kit(on the iphone only
but cocoa has a similar lib')
includes ui.view.controller
which is a generic controller to subclass .
. controllers are composable,
so their code can be shared .
4.23:
. the limits of ints are in limits.h,
while those of floats are in floats.h:
. within the float limits there are often limits for each of
[ FLT -- float
, DBL -- double
, LDBL -- long double]
FLT_ROUNDS = rounding towards where?
( zero: 0
, nearest: 1
, +inf: 2
, -inf: 3
, others: impl'dep
) .
. when you a see a * in the following,
it refers to above type symbols
{ FLT , DBL , LDBL, FLT_ROUNDS }:
*_EPSION -- steps between discrete values
(smallest for x+1.0 /= x)
*_MIN -- smllest available fraction
= 10**MIN_10_EXP
*_MAX -- largest available number
= 10**MAX_10_EXP
FLT_RADIX = {2(bits), 8(bytes), or 10(bcd)}
-- the base around which float limits are defined .
*_DIG
-- #[available fraction digits] .
*_MANT_DIG
-- #[digits in mantissa of sci'notation using base FLT_RADIX]
*_{MIN,MAX}_EXP
-- exponent to the base FLT_RADIX of
smallest fraction or largest number;
eg for 32bit and 64bit in base 2: -125, 128; -1021, 1024 .
*_{MIN,MAX}_10_EXP
-- exponent to the base 10 of smallest fraction or largest number .
. unsigned does modulo math
(doesn't overflow with warning;
instead, it's wrapping around range)
. if you mix unsigned with signed,
the natural reaction is to coerce to signed,
but c's implicit coercion does the opposite:
(unsigned > -1) is false in c !
. you'll need to explicitly convert:
((signed)unsigned > -1) is true .
. the reason c does that
is that the use of unsigned is specialized to do
modulo math
so mixing negatives would happen only in the
rare case of
using unsigned to save a bit of space
or when you were using that elegant c idiom
where
-1 can always stand for the largest unsigned value
of any range size (byte, word, long) .
. depending on the implementation,
c's char may be any of
{ signed,
, unsigned
, signed restricted to range non-neg'
} .
. to see your impl's style, check for:
char c = -1;
int i = c;
print i; ->
{ -1 --. char is signed .
, 255 --. is unsigned .
, err --. is signed with range non-neg' .
} .
. what shows when you negate a signed char?
besides testing for sizes
you can depend on limits.h .
4.24:
. (void *) is a generic ptr
but pointing only to obj's not functions;
all pointers to function
must be declared as being a certain signature
(a declaration of param' and return types) .
. while (void *) can be declared,
(void *)[] cannot .
4.25:
extern T array[]
--. this is a declaration;
the definition that matches it
must give a range along with an init
or the init must implicitely define the range .
. page#113 has some bizarre predictions about
multi-dimension arrays;
eg, (*(a+1)+2) should still be for &a[1][2]
as if *(a+1) can get an element of the array
but only if it's not followed by
more pointer-legal arithmetic
in which case it acts as if
multi-dim arrays are impl'd as
array of pointer to array .
. it does follow from the definition of
array subscription:
a[i][j] = *(*(a+i)+j)
. what makes it confusing is the
convenience factor:
it has rules that follow no particular model,
choosing instead to
reduce the amount of programmer writing .
. when enum's are intro'd into a scope
(by giving a var an enum.type )
no new symbols can take the names of
any of the enum`s literals .
4.26: sci.addn/dev.c/apple`s use of it:
. here they used !(s) not !s :
#if !(defined(KLD) && defined(__STATIC__))
4.27:
. pointers can refer to struct internals
except bit fields .
. pointers in rec's are like in arrays;
so, p1 > p2 if
field p2 is at a field declared later than
field p1 .
syntax within struce:
unsigned field : fieldsize;
. if no name then the field is for padding;
if no name and fieldsize = 0
then padding is sized for word completion,
ie, for making the next field be word-alligned .
. there are some drawbacks to bit fields:
they can't cross word boundaries,
so to be space-efficient
they may depend on the platform`s wordsize .
eg, 3bit * 3 fit into 16 but not 8 bit words .
the authors weren't convincing? web:
. ah, they didn't mention the concurrency issue,
but I would be surprised if
the compilers wrote inefficient code:
isn't it just shorthand for the usual
bit manipulations with masks?
is that this effects bit ordering too:
if you store data as bits made on one machine
then you can't portably use that data in binary form .
the BitField
4.29: news.addn/dev.mac
. how to write math algorithms
with numbers from user dialog ...
. did you actually want to use NSNumber in your algorithms?
it might be simpler to reuse your existing algorithms:
. your obj'c code accepts NSNumber
then converts it to a c`type,
then returns the result boxed in an NSNumber
with (NSNumber *)numberWithFloat:(float)value .
4.30:
. unions are like arrays in that
a ptr to union is implicitly a
ptr to union's first member
(an only member in the case of union);
union is like a struct in that
it uses the ( ptr->field ).syntax .
. in the case of unions,
the field selector is identifying a type
rather than a location
but both use a field symbol to do his .
but I would be surprised if
the compilers wrote inefficient code:
isn't it just shorthand for the usual
bit manipulations with masks?
. there are potentially severe thread safety issues. ah, the reason they mention endianess or byte ordering,
(especially on multiprocessor systems)
due to the fact that most machines
cannot manipulate arbitrary sets of bits in memory,
but must instead load and store whole words;
e.g. struct foo
{ int flag : 1;
int counter : 15;
}
. on most machines it is impossible to
load and store flag and counter separately .
. (In order for this to be thread-safe,
you would need to lock and unlock
the mutex around all accesses to both
flag and counter,
even if counter doesn't itself need to be thread-safe.).
is that this effects bit ordering too:
if you store data as bits made on one machine
then you can't portably use that data in binary form .
the BitField
. less widely used then one might expect,
for two reasons:
* It is unacceptable for portable code
(especially when accessing fields within persistent data structures)
because C does not define whether or not
the LSB or MSB is mentioned first
(this is in addition to any endianality issues).
* It is often discouraged for system code
(which often need not be portable)
as many hardware registers are write-only,
have different meanings for read/write,
and/or have destructive read
-- making the ReadModifyWrite implemenation of
BitField modifications
unsuitable for such registers.
4.29: news.addn/dev.mac
. how to write math algorithms
with numbers from user dialog ...
. did you actually want to use NSNumber in your algorithms?
it might be simpler to reuse your existing algorithms:
. your obj'c code accepts NSNumber
then converts it to a c`type,
then returns the result boxed in an NSNumber
with (NSNumber *)numberWithFloat:(float)value .
4.30:
. unions are like arrays in that
a ptr to union is implicitly a
ptr to union's first member
(an only member in the case of union);
union is like a struct in that
it uses the ( ptr->field ).syntax .
. in the case of unions,
the field selector is identifying a type
rather than a location
but both use a field symbol to do his .
5.1: c's h&s (harbison & steele) :
c`function ptr can be assigned either a function
or ptr to same
as they mean the same thing:
ptr= f;
ptr =&f;
. to ignore a return
cast it to void .
[. obj'c also has meanings for nil and null .]
. what apple calls a type cluster
c's h&s (harbison & steele) or ansi
calls a type composite ?
[7.12: the ansi language
is using that term to clarify type compatability;
eg, given two file scope decl's:
both of the types it was constructed from .
]
. ansi c forbids mixing type qualifiers with typedefs;
eg,
typedef int num;
unsigned num x; -- illegal .
. to use xcode with other projects,
ask for a new project
then find where the files are,
if adding files isn't allowed,
then paste the reused project`code
into your new project`s files .
5.2:
. malloc can be very wasteful
as the mem needs to start on the largest
alignment modulus; eg, 8 bytes or larger .
. cast a ptr to small
as although casting a ptr to large will be permitted
it can result in an alignment violation,
eg, longs need to be on mod 0,
so converting a byte on mod 1
and then doing a long operation
is either impl'dependent or crashing;
or, the system could change the obj's
mod location
which means the pointer value changes across castings
ie, it's no longer true that
cast( inverse cast(x)) = x .
. function pointers are not mixable with obj'ptr's,
-- only obj' ptr's may pass and be assigned
(void *) -- that being the ansi version of
"(generic ptr) (aligned to handle obj of any size) .
. the need for declaring lib function with inout types
includes knowing when to use null
. usually a data ptr is not a function pointer .
5.3:
. why would c users want to convert unsigned to signed
even if overflow makes it look negative?
that is a quick way to tell if you're
halfway through your unsigned`s range:
. ansi c has a conversion a bug:
on each system, check to make sure
you don't use unsigned {short, char} if it's
impl'd as int`size
because only then it's surprisingly
coerced to unsigned int,
meaning that
-(unsigned short|int)
has a non-intuitive result .
. the way to deal with short's = int's
is to convert explicitely to long
or something you know is
one size larger than the short you're converting .
. for each platform,
test the sizes of your native types,
and work only with types you define as a certain size,
not the native types that can vary in size .
5.5:
. with unsigned {int, long},
the coercion can go impl-dep to either {long, unsigned};
so, don't think of unsigned as
absolutely positive .
. if unsigned int is large
(negative when interpreted as int)
then comparing it to long
will auto'ly convert it to a
negative long .
--. the coercion is needed because
{unsigned, long} are not the same type
however if int`size = long`size
then things become normal?
either ansi, h&s, or myself are bonkers .
news.addn/dev.c/stdint.h`int32_t:
. there's no C standard type for "32 bit int" ?
C99 fixed that:
. include stdint.h, then use either uint32_t or int32_t.
news.addn/dev.c/concurrency:
5.6: stdio.h`gets is strongly discouraged:
. it reads a line from the standard input
and stores it in the caller's fixed-sized buffer
and opens a gate for exploiting computer security through a buffer overflow .
. It is left in the C89 and C99 standards for backward compatibility
. Many development tools such as GNU ld
emit warnings when code using gets is linked.
. to avoid buffer overflow bugs, a simple alternative is fgets:
replace
c`function ptr can be assigned either a function
or ptr to same
as they mean the same thing:
ptr= f;
ptr =&f;
. to ignore a return
cast it to void .
[. obj'c also has meanings for nil and null .]
. what apple calls a type cluster
c's h&s (harbison & steele) or ansi
calls a type composite ?
[7.12: the ansi language
is using that term to clarify type compatability;
eg, given two file scope decl's:
int f(int (*)(), double (*)[3]);the resulting composite type is:
int f(int (*)(char *), double (*)[]);
int f(int (*)(char *), double (*)[3]);ie, that composite type is type compatable with
both of the types it was constructed from .
]
. ansi c forbids mixing type qualifiers with typedefs;
eg,
typedef int num;
unsigned num x; -- illegal .
. to use xcode with other projects,
ask for a new project
then find where the files are,
if adding files isn't allowed,
then paste the reused project`code
into your new project`s files .
5.2:
. malloc can be very wasteful
as the mem needs to start on the largest
alignment modulus; eg, 8 bytes or larger .
. cast a ptr to small
as although casting a ptr to large will be permitted
it can result in an alignment violation,
eg, longs need to be on mod 0,
so converting a byte on mod 1
and then doing a long operation
is either impl'dependent or crashing;
or, the system could change the obj's
mod location
which means the pointer value changes across castings
ie, it's no longer true that
cast( inverse cast(x)) = x .
. function pointers are not mixable with obj'ptr's,
-- only obj' ptr's may pass and be assigned
(void *) -- that being the ansi version of
"(generic ptr) (aligned to handle obj of any size) .
. the need for declaring lib function with inout types
includes knowing when to use null
. usually a data ptr is not a function pointer .
5.3:
. why would c users want to convert unsigned to signed
even if overflow makes it look negative?
that is a quick way to tell if you're
halfway through your unsigned`s range:
(int) x.unsigned < 0 ?
print "(my unsigned int is near overflow) .
5.4:. ansi c has a conversion a bug:
on each system, check to make sure
you don't use unsigned {short, char} if it's
impl'd as int`size
because only then it's surprisingly
coerced to unsigned int,
meaning that
-(unsigned short|int)
has a non-intuitive result .
. the way to deal with short's = int's
is to convert explicitely to long
or something you know is
one size larger than the short you're converting .
. for each platform,
test the sizes of your native types,
and work only with types you define as a certain size,
not the native types that can vary in size .
5.5:
. with unsigned {int, long},
the coercion can go impl-dep to either {long, unsigned};
so, don't think of unsigned as
absolutely positive .
. if unsigned int is large
(negative when interpreted as int)
then comparing it to long
will auto'ly convert it to a
negative long .
--. the coercion is needed because
{unsigned, long} are not the same type
however if int`size = long`size
then things become normal?
either ansi, h&s, or myself are bonkers .
news.addn/dev.c/stdint.h`int32_t:
. there's no C standard type for "32 bit int" ?
C99 fixed that:
. include stdint.h, then use either uint32_t or int32_t.
news.addn/dev.c/concurrency:
I've found more problems by running withlib.addn/dev.c/C Programming/C99 Reference
fewer threads than processors.
Otherwise, you aren't necessarily getting
true concurrency.
Running ten threads on a single processor
isn't going to help you find some of the
pesky concurrency issues that arise from
true parallel execution.
Of course, one should run with
more threads than processors to test that as well.
5.6: stdio.h`gets is strongly discouraged:
. it reads a line from the standard input
and stores it in the caller's fixed-sized buffer
and opens a gate for exploiting computer security through a buffer overflow .
. It is left in the C89 and C99 standards for backward compatibility
. Many development tools such as GNU ld
emit warnings when code using gets is linked.
. to avoid buffer overflow bugs, a simple alternative is fgets:
replace
gets(char buffer[BUFFERSIZE]);with code of the form
char buffer[BUFFERSIZE];. one must keep in mind that the
fgets(buffer, sizeof(buffer), stdin);
fgets(buffer, sizeof buffer, stdin) call
differs from gets(buffer)
differs from gets(buffer)
not only in buffer overflow protection,
but also in that fgets(buffer, sizeof buffer, stdin)
preserves the terminating newline
(if the input line is terminated by a newline),
while gets(buffer) discards it.
5.6: the 10 most Common Programming Mistakes in C++
. most of them are from thinking c is Basic
. not sure why it would be common to
put a semicolon after a loop header .
. I was caught by a float not taking 1/2 correctly:
those are a division of integers
which returns an integer !
(stupid like python?
this tradition in C is how python got stupid!)
5.7: c precedence is understandable:
f g h (x) is f(g(h(x)))
ie each unary operator binds to an operand
before being used as an operand .
. just think of the post-{incr, decr}
as being a unary that is placed on
the opposite side of the operand
but stays in the same order with the other unary's .
. the usual associative (biop grouping)
is left to right -- the way we read .
. assignmment is saying how things can be equal
so it's not assoc right to left
but is a mult-stmt(concurrent):
a=b=c is really {a,b}= c
. the only other right to left assoc is (?:)
as that is a trinary
more like a unary than a binary .
but also in that fgets(buffer, sizeof buffer, stdin)
preserves the terminating newline
(if the input line is terminated by a newline),
while gets(buffer) discards it.
5.6: the 10 most Common Programming Mistakes in C++
. most of them are from thinking c is Basic
. not sure why it would be common to
put a semicolon after a loop header .
. I was caught by a float not taking 1/2 correctly:
those are a division of integers
which returns an integer !
(stupid like python?
this tradition in C is how python got stupid!)
5.7: c precedence is understandable:
f g h (x) is f(g(h(x)))
ie each unary operator binds to an operand
before being used as an operand .
. just think of the post-{incr, decr}
as being a unary that is placed on
the opposite side of the operand
but stays in the same order with the other unary's .
. the usual associative (biop grouping)
is left to right -- the way we read .
. assignmment is saying how things can be equal
so it's not assoc right to left
but is a mult-stmt(concurrent):
a=b=c is really {a,b}= c
. the only other right to left assoc is (?:)
as that is a trinary
more like a unary than a binary .
5.7:
. c can do f(x).c:
it means return the function result's component;
ie, toss the rest of the result's struct .
. how to define
fun can be assigned
vs
fun is not allowing redef?
. param's can be arrays
but only the pointer is shared not the obj
so of you want to ensure that
an array passed as an arg
is not going to be modified,
then you should make a copy,
and then pass that as the arg .
5.8:
. div of unsigned or positive rounds to zero,
but {div, mod} of negatives has an impl'dep' result,
and can cause overflow;
(a/b)*b + a%b = a
--. div and mod are often part of the same operation
at the machine instruction level .
. (ptr -ptr) is type stddef.h`ptrdiff_t .
5.12:
. shifting signed int's isn't portable,
unless sure non-neg, which you can't be
if also doing left-shifts .
. left shift is mult regardless of endianess?
by definition .
page#192: part of binary gcd:
. determine the largest power of two
that divides both x, y:
--. suggests endian ness ddoesn't matter,
for any unsigned type .
. conversions that are needed between
{unsigned, signed}
also apply to relational operators
{ less than, greater than, etc }
because they are impl'ed by
an arithmetic subtraction .
. as expected,
bit-wise op's differ from boolean op's
also in eval'ing all args,
rather than just eno' to determine boolean outcome;
eg,
a&&b doesn't eval b if a is false,
(nor create any of its sideaffects)
whereas a&b evals both
regardless of whether (a == 0)
. also, bool's return {false = 0, true = 1}
rather than letting any non-zero mean true .
. the char value '\0' means false .
. &&`prec > ||`prec .
. for some limits on const expr's
the issue is how to compile on host
something that still applies to target .
. shift of x.unsigned by n
is equal to x * 2**n,
where positive n gives a left shift .
5.17:
. your impl.file should include its own header file
to let the compiler check whether your
prototype is matching .
5.18: sci:
. to have macro's eval arg's only once
even when the arg is used multiple times,
declare a local,
use the arg only once to assign to the local,
then the local can safely be used repeatedly .
5.18:
. c lib's reserve all id's starting with underscore
_ID
. to impl' exceptions,
c'library routines use errno;
set this to 0 then see if its non-zero after a lib' call:
situ= "info about this call"
errno=0;
-( make your lib' call now )-
if(errno) perror (situ)
--. calling perror with siturr
outputs to stderr the string in situ, a "(:),
and the return of strerror(errno);
ie, it relates the error's context
with what the system wants to say about the error .
5.19:
. c string needs a major safety wrapper .
5.25:
. table driven methods speed up a function
by impl'ing points as an array
. compilers did that:
fsa as function
was impl'd as table
or array with 2 or more params .
c's conventional ordering:
. includes
, const
, macro
, types
, import signatures
, export signatures
, private vars and functions .
5.29:
. c`string's append is not adding the 0 at end,
the compiler adds this to literals
but unless you init'd your char array
with a string literal
it does not have the required 0 at the end .
. cat(a, b) means
a`= (append b to a) .
. catn does supply a 0-end
if it doesn't find one by the given limit .
cat(a,b,n) means
a`= (append b#(1..n) to a)
where n can exceed the length of b
in which case n is replaced with b`len .
. the cat functions are not overlap-safe;
ie, (a) and (b) should not be
pointers into the same string .
. lexicographic ordering implicitely uses a 0-end
which has a lower value than any other char
and 0-ends the string so
this implies that an equal but shorter string
is a lesser string:
cmp(a,b) is b-a; ie,
(uses eos.flag -- set when end of either string is accessed):
for i= 1.. eos:
temp`= b#i - a#i;
temp =/= 0 ? return temp
return 0 .
6.1:
. c`calloc zeroes mem but a bit-wise zeroing of a float
is not equal to float`0 .
(because even when the mantissa is zero, the exponent is non-zero?)
6.2:
. steele p 303 shows how file access is supposed to work with errno.h .
binary.files can seek to offset from begin, current, end;
text can seek to end, begin, or
offset from a begin given by ftell -- uses errno.h .
. text is complicated by impl-dep' line-structuring .
. ftell, fseek use a long.type to point in file;
if you suspect file will be very large,
then use fgetpos, fsetpos .
. signal handlers can call exit;
causing the c program to exit without finishing;
so, all mem' alloc'ers and other cleanup routines
should register with atexit .
6.14:
. C considers all non-alpha'num symbols to be punctuations
but it needs recognize only the ones used in a C program .
. consider too that the ones used in a C program
can depend on the locale;
eg, curly braces can be replaced with an ANSI substitute .
c's disciplined typedefs got lost in C++:6.4:
. C++ is not a superset of C,
as C does not allow a given typedef
to appear more than once in the same scope;
whereas, C++ handles typedefs and type`names
without such noise:
(e.g., common typedefs that occur in multiple header files
should be guarded by preprocessing directives:
#ifndef MYINT_T
#define MYINT_T
typedef int MyInt;
#endif
) .
6.21: c/wheeler`secure prog'ing practices
[@] 2009.9/addn/dev.mac
news.obj'c/exemplary obj'c code projects:
6.6:
. Objective-C ActiveRecord. Objective-C SQLitePersistentObjects7.8:
directory of obj'c proj's
obj'c/do all text the iphone way:
6.7:
lessons from www.mac-developer-network.com:
. the way cocoa text is modified by attributed strings:
this is not supported on iphone,
which instead is expecting you to evolve to modern web programming
where the real deal is css:
marking what class an object is in;
-- eg, emphasized, or literal code; --
and then having a generally usable map:
eg, emphasized.class -> attribute(fonts, colors, sizes) .
6.23:
dev.mac/c burdened the move from ppc to intel:
[!] aka: move to intel was a "(c isn't portable!):
. I had wondered why developers would care about
moving to new platform; but after learning c,
all I kept hearing was "(c isn't portable!) .
. if the program uses c floats, or even some other c features,
their code is not portable,
and their testing may consist of nothing more than beta users .
. c can do f(x).c:
it means return the function result's component;
ie, toss the rest of the result's struct .
. how to define
fun can be assigned
vs
fun is not allowing redef?
. param's can be arrays
but only the pointer is shared not the obj
so of you want to ensure that
an array passed as an arg
is not going to be modified,
then you should make a copy,
and then pass that as the arg .
5.8:
. div of unsigned or positive rounds to zero,
but {div, mod} of negatives has an impl'dep' result,
and can cause overflow;
(a/b)*b + a%b = a
--. div and mod are often part of the same operation
at the machine instruction level .
. (ptr -ptr) is type stddef.h`ptrdiff_t .
5.12:
. shifting signed int's isn't portable,
unless sure non-neg, which you can't be
if also doing left-shifts .
. left shift is mult regardless of endianess?
by definition .
page#192: part of binary gcd:
. determine the largest power of two
that divides both x, y:
[common power of 2]`= 0;
while( ((x|y)&1) == 0 )
{ x`>>1, y`>>1
; [common power of 2]`+1
}
gcd with shift:--. suggests endian ness ddoesn't matter,
for any unsigned type .
. conversions that are needed between
{unsigned, signed}
also apply to relational operators
{ less than, greater than, etc }
because they are impl'ed by
an arithmetic subtraction .
. as expected,
bit-wise op's differ from boolean op's
also in eval'ing all args,
rather than just eno' to determine boolean outcome;
eg,
a&&b doesn't eval b if a is false,
(nor create any of its sideaffects)
whereas a&b evals both
regardless of whether (a == 0)
. also, bool's return {false = 0, true = 1}
rather than letting any non-zero mean true .
. the char value '\0' means false .
. &&`prec > ||`prec .
. for some limits on const expr's
the issue is how to compile on host
something that still applies to target .
. shift of x.unsigned by n
is equal to x * 2**n,
where positive n gives a left shift .
5.17:
. your impl.file should include its own header file
to let the compiler check whether your
prototype is matching .
5.18: sci:
. to have macro's eval arg's only once
even when the arg is used multiple times,
declare a local,
use the arg only once to assign to the local,
then the local can safely be used repeatedly .
5.18:
. c lib's reserve all id's starting with underscore
_ID
. to impl' exceptions,
c'library routines use errno;
set this to 0 then see if its non-zero after a lib' call:
situ= "info about this call"
errno=0;
-( make your lib' call now )-
if(errno) perror (situ)
--. calling perror with siturr
outputs to stderr the string in situ, a "(:),
and the return of strerror(errno);
ie, it relates the error's context
with what the system wants to say about the error .
5.19:
. c string needs a major safety wrapper .
5.25:
. table driven methods speed up a function
by impl'ing points as an array
. compilers did that:
fsa as function
was impl'd as table
or array with 2 or more params .
c's conventional ordering:
. includes
, const
, macro
, types
, import signatures
, export signatures
, private vars and functions .
5.29:
. c`string's append is not adding the 0 at end,
the compiler adds this to literals
but unless you init'd your char array
with a string literal
it does not have the required 0 at the end .
. cat(a, b) means
a`= (append b to a) .
. catn does supply a 0-end
if it doesn't find one by the given limit .
cat(a,b,n) means
a`= (append b#(1..n) to a)
where n can exceed the length of b
in which case n is replaced with b`len .
. the cat functions are not overlap-safe;
ie, (a) and (b) should not be
pointers into the same string .
. lexicographic ordering implicitely uses a 0-end
which has a lower value than any other char
and 0-ends the string so
this implies that an equal but shorter string
is a lesser string:
cmp(a,b) is b-a; ie,
a<b -> negative
a>b -> positive
a=b -> zero
. abstract algorithm for c's string compare(uses eos.flag -- set when end of either string is accessed):
for i= 1.. eos:
temp`= b#i - a#i;
temp =/= 0 ? return temp
return 0 .
6.1:
. c`calloc zeroes mem but a bit-wise zeroing of a float
is not equal to float`0 .
(because even when the mantissa is zero, the exponent is non-zero?)
6.2:
. steele p 303 shows how file access is supposed to work with errno.h .
#include <errno.h>
#include <stdio.h>
FILE *open_input(char * filename)
{
FILE *f;
errno = 0;
f= fopen (filename, "r");
if (f == NULL) fprintf(stderr, %s failed: %s\n", filename, strerror(errno));
return f;
}
int close_file(FILE *f)
{
int s= 0;
if (f == NULL) return 0;
errno = 0;
s= fclose(f);
if (s == EOF) perror("close failed");
return s;
}
. files can be opened as text or binary;binary.files can seek to offset from begin, current, end;
text can seek to end, begin, or
offset from a begin given by ftell -- uses errno.h .
. text is complicated by impl-dep' line-structuring .
. ftell, fseek use a long.type to point in file;
if you suspect file will be very large,
then use fgetpos, fsetpos .
. signal handlers can call exit;
causing the c program to exit without finishing;
so, all mem' alloc'ers and other cleanup routines
should register with atexit .
6.14:
. C considers all non-alpha'num symbols to be punctuations
but it needs recognize only the ones used in a C program .
. consider too that the ones used in a C program
can depend on the locale;
eg, curly braces can be replaced with an ANSI substitute .
c's disciplined typedefs got lost in C++:6.4:
. C++ is not a superset of C,
as C does not allow a given typedef
to appear more than once in the same scope;
whereas, C++ handles typedefs and type`names
without such noise:
(e.g., common typedefs that occur in multiple header files
should be guarded by preprocessing directives:
#ifndef MYINT_T
#define MYINT_T
typedef int MyInt;
#endif
) .
6.21: c/wheeler`secure prog'ing practices
[@] 2009.9/addn/dev.mac
news.obj'c/exemplary obj'c code projects:
6.6:
. Objective-C ActiveRecord. Objective-C SQLitePersistentObjects7.8:
directory of obj'c proj's
obj'c/do all text the iphone way:
6.7:
lessons from www.mac-developer-network.com:
. the way cocoa text is modified by attributed strings:
this is not supported on iphone,
which instead is expecting you to evolve to modern web programming
where the real deal is css:
marking what class an object is in;
-- eg, emphasized, or literal code; --
and then having a generally usable map:
eg, emphasized.class -> attribute(fonts, colors, sizes) .
6.23:
dev.mac/c burdened the move from ppc to intel:
[!] aka: move to intel was a "(c isn't portable!):
. I had wondered why developers would care about
moving to new platform; but after learning c,
all I kept hearing was "(c isn't portable!) .
. if the program uses c floats, or even some other c features,
their code is not portable,
and their testing may consist of nothing more than beta users .
7.09: c`lib:
. std arg.h is not needed:
for vari.arg, use lists ,
signal.h is not portable
-- make your own even5 model and map that to currrent platform .
size-t is a safe subcript type
but using size-t is unsigned ;
eg, not as easy to work with as int, like when testing for EOF .
ptrdiff-t is lame needing to include neg's,
it's half the size it needs to be!
wchar-t need not be greater than 8bit!
(why bother?) give it up:
just use int32 to rep wordcode
which includes unicodew depending on type -tag
function proto-typing not helpful for vari-arg
functions .
offsetof(type, field) is good for init for table driven .
for export to text file,
terminate the last line with a newline,
(eof is not eno' to delimit a string)
don't expect whitespace preceding a newline to be filed,
keep line length less than 510
empty files may be deleted: test for file existence!
-- the book's tests could show lib being used
and prove curr platform's lib .
. tcl's string interface may have been motivated by
unix's original preference that all files be text (string in a file)
7.10:
. the unix tool-oriented approach is what inspired
tcl's use of strings-only parameters for applications .
. in unix your tool is supposed to use std I/O
which is text -- char strings --
and then clients combine tools by pipes and redirects .
. the addx approach is to use the
human client's presentation agent to
recognize any text input and convert it into etrees,
similar to the way lisp`read does,
converting string into trees of symbols .
. so then all tools are expecting std I/O to be lisp's s-expressions .
. when storing binary files, a platform may pad your file with nulls .
. streams are type"file that include buffering .
. traditional unix was not buffered, but c is .
. dont make any assumptions about file names:
c has a [create a new filename ] function,
so use that to ask for a filename, and then use your own directory system,
to map those filenames to what the user wants .
6.21: wheeler's guide:
. ignored resource limits can crash system .
. the umask (user`file mode creation mask )
limit# data`length -- Avoid buffer overflow.
[validate whitelists rather than rejecting blacklists:]
. define what an acceptable input is,
and reject anything that doesn't match.
. buffer overflow is the primary programmatic error
[in a unix-style environ being programmed with C ]
Make sure that long inputs (and long intermediate data values)
can't be used to take over your program.
Carefully call out to other resources.
Limit their values to valid values
(in particular be concerned about metacharacters),
and
check all system call return values.
[--. major problem with C is programmer not handling c-style exceptions
(checking return codes and certain global var's) .]
. C makes it easy to ignore critical error situations.
[7.12:
. C does have an exception handling system,
and it works by checking the function's returned error code,
or its effect on errno.h .
]
Do not ignore return values;
Look up each operation's semantics in its documentation.
. Don't ignore the difference between {signed, unsigned} values.
One complication in C and C++ is that the character type "(char)
can be signed or unsigned (depending on the platform).
When a signed char with its high bit set is saved in an integer,
the result will be a negative number;
in some cases this can be exploitable.
. for buffers, pointers, and casts
when dealing with character data > 127 (07f#16),
use "(unsigned char) instead of {char, signed char} .
. when working with the filesystem,
be aware of strange char's in the filename .
[7.13:
. get all your names through C's [unique filename].function
or haggle with the user about a reasonable filename
on a per-platform basis .
]
9.13: Validate input# platform-provided services:
. just as you unit-test your own units,
you should also run tests on the units you import .
. this of course, is done during installation,
when your installer actually has access to
the platform it's depending on .
. if you are exposed to OS's where DLL he'll is a problem,
you may want to test during each startup,
that the units you tested
are the same ones that are still there .
6.21: Validate input# filenames
[9.14:
. remote users who have partially penetrated the system
may try poisoning a filename to complete the entry .
9.13:
. if the filename is being passed to a library function,
that function may in turn call the unix shell,
which is very vulnerable to semantic attacks
where non-alphanumeric characters are misunderstood
as being metacharacters,
ie, part of the command syntax rather than the filename .
. the mac terminal via the finder
lets you safely use any filename
by escaping all the the possible metacharacters;
perhaps it can be programmatically used via scripting interface;
but, beware using interfaces meant only for gui access .
9.14:
What makes the shell metacharacters particularly pervasive
is that several important library calls, such as popen(3) and system(3),
are implemented by calling the command shell,
meaning that they will be affected by shell metacharacters too.
Similarly, execlp(3) and execvp(3) may cause the shell to be called.
and use execve(3) directly in C when trying to spawn a process .
. esp'ly avoid using system(3) since it uses the shell to expand characters;
so, there is more opportunity for mischief than with execve(3) .
]
Invalid character encoding:
For example, a program may believe that the filename is UTF-8 encoded,
but it may have an invalidly long UTF-8 value
[not within the single-byte ascii range,
instead consisting of multipe bytes] .
Unix-like systems generally forbid filenames from including
either the NIL character (the end of the name)
or the '/' character (the directory separator).
However, they often permit anything else;
moreover, names can be supplied by the attacker
that have not been filter by the filesystem;
and, there are many characters that can cause problems:
. if the name included "../"
(the symbol for a current directory's enclosing directory),
then the filename may be misunderstood as including a pathname .
It's best to prohibit any change in directory,
e.g., by not including "/" in the set of legal characters .
Filenames with control characters and white space
Filenames with any other non-alphanumeric character:
. operators and punctuations can be significant to internal data formats,
eg, used by the sh.shell: & ; ` ' \ " | * ? ~ < > ^ ( ) [ ] { } $
eg, some shells use: ! . # - --
. for similar attacks on SQL, see db primer,
. "(globbing) is the use of wildcard characters for refering to sets of files;
For example, the command "(ls *.png)
does a glob on "(*.png) to list all PNG files.
. this capability can easily be abused .
. the command shells perform globbing by default,
and in C you can request globbing using (for example) glob(3).
If you don't need globbing,
just use the calls that don't do it (e.g., fopen(3))
or disable them (e.g., escape the globbing characters in a shell).
Validate input# environment variables
Normally, environment variables shoulld be accessed only through
the standard access routines;
For example, in C, you should get values using getenv(3),
set them using the POSIX standard routine putenv(3)
or the {BSD, linux} extension setenv(3)
and eliminate environment variables using unsetenv(3).
However, crackers can directly control
the environment variable data area passed to a program using execve(2).
This permits subtle attacks which can only be understood by
knowing how environment variables really work.
see linux`environ(5) for a summary about how environment variables really work.
[. the mac's man page doesn't mention these bugs .]
. the most dangerous implication of this format
is that it allows multiple entries with the same variable name,
to have different values (e.g., more than one value for SHELL).
While typical command shells prohibit doing this,
a locally-executing cracker can create such a situation
using execve(2).
The problem with this storage format (and the way it's set)
is that a program might check one of these values
(to see if it's valid)
but actually use a different one (with an invalid value).
In Linux, the GNU glibc libraries try to shield programs from this;
GNU`glibc 2.1's implementation of getenv
will always get the first matching entry,
setenv and putenv will always set the first matching entry,
and unsetenv will actually unset all of the matching entries
However,
some programs go directly to the environ variable
and iterate across all environment variables;
in this case,
they might use the last matching entry instead of the first one.
As a result,
if checks were made against the first matching entry instead,
but the actual value used is the last matching entry,
a cracker can use this fact to circumvent the protection routines.
. suppose we want to access the shell environment variable `$HOME'.
char *string;
string = getenv("HOME");
. `string' is now a pointer to static but public data.
You should not use `string' as if it were you're own property;
because it will be used again by the system.
. Copy it's contents to another string before using the data:
char buffer[500];
strcpy (buffer,string);
.
how to Extract & Erase environment variables:
. see unistd.h
. for Linux, see clearenv()
. see {linux`environ(5), mac`environ(7)} for a list of
common environment variables that you might want to set.
One environment value you'll almost certainly re-add is PATH,
PATH should not include the current directory
and usually be something simple like ``/bin:/usr/bin''.
Typically you'll also set TZ (timezone)
and IFS (to its default of "( \t\n) -- space is the first character)
Validate input# current directory:
Consider explicitly changing directories at program startup
to an appropriately fully named directory (using chdir(2)) .
Validate input# concurrency
. concurrency-related inputs:
signals,
memory maps (mmaps),
IPC, [interprocess communication]
pending timers,
the scheduling priority .
There comes a time when you want to read and write to and from files so that the information is shared between processes. Think of it this way: two processes both open the same file and both read and write from it, thus sharing the information. The problem is, sometimes it's a pain to do all those fseek()s and stuff to get around. Wouldn't it be easier if you could just map a section of the file to memory, and get a pointer to it? Then you could simply use pointer arithmetic to get (and set) data in the file.
Here is the example of using mmap() to implement file copy (e.g., UNIX cp) .Two different programs can also map the same file, for example, anduse this as a form of inter-process communication (but making sure tocontrol concurrency, e.g., using semaphores).
Validate input# client-side scripts:
. a webpage downloaded by your browser or other web.app
may include scripts that your user can activate .
. it's not eno' to protect your user from the effects of scripts;
you also have to insure that such scripts do not send
malicious requests to other nodes on the internet .
. the user may base the trustworthiness of a site on a familiar name,
so to avoid semantic attacks, you have to check for when
code or URL's that appear to do one thing are actually doing something else .
eg, http://www.trustedsite.com@www.evil.com
appears at a glance to visit trustedsite.com,
but is instead just a mailbox name for evil.com .
. any trusted site containing the letter"o
could easily be mistaken for a site with nearly the same name
that replaced letter o with zero .
. another thing to warn your client about
is the use of URL names using international characters,
as some can look very similar to ASCII char's .
Validate input# client-side cookies:
Another form of data available to web-based applications are cookies.
Again, users can provide arbitrary cookie values,
so they cannot be trusted unless special precautions are taken.
. given privacy concerns, they cannot be counted to be present anyway .
Note that to use cookies,
some browsers may insist that you have a privacy profile
(named p3p.xml on the root directory of the server).
. persistent cookies are those that last beyond a current session .
. U.S. agencies are usually forbidden from using persistent cookies:
9.4: bk.addn/dev.mac:
. the cocoa exception system is at the top level
(even main doesn't have a chance to handle these?)
. the working exception system is c's usual:
functions that may fail indicate this by returning nil or some truth value .
. the convention is to have obj`factories return {nil, obj},
hence, unlike lisp, nil can't be used to mean no value
(it already means an exception was raised);
so, to request a default value, give the parameters an empty enclosure .
. cocoa strings that would seem to accept string literals
actually need global const string (they don't copy the obj)
while literals are local to current scope .
. always name string literals to guard against spell'errors .
9.5:
nsscriptcommand is subclassed to be scriptable,
9.6:
. c params don't take arrays
treated as ptr,
param(z * a[n]) = -- .#(0..n-1).z
param(z a[][n]) -- .#(0..n-1).#(0..n-1).z
c is returning a ptr to local?
ok when obj is static
(actually a private global)
z (*f)() = f.().z
c fun uses paren's as part of type
like array brackets .
f() = f -- called wo arg,
f = f`body .
. what c ptr has is a generic arrangement,
where the ptr can mean many things:
unlike oop
there is no help from type`mgt in guarding against
going out of bounds of an array .
. think of a ptr to ptr as most likely being
an array of ptr,
not a handle
. c lets you describe both with the same syntax .
similar to a handle is the ptr's
use a meaning an out-mode param .
. ptr ptr allows sub to modify a caller's ptr's .
. also a ptr , can be an array
so ptr ptr often inout array .
or inout ptr to array (sub then can
change index for caller ) .
array of string literals rally arranges array of ptr to string
. ptrs are a sort of number
so can mix ptr, literal 0 for null, and string literals
(actually ptr's to static constants)
if c`ref arg is not meant to be inout then syntax:
const t * obj; = obj./.t(rom)
for ptr itself is const then syntax:
t * const obj; = obj./(rom).t .
-- notice array names are const ptrs
so this is providing an arg type that does match .
c++ char array obj's can be modified
9.8: bk:
. obj's that are first class will need to adopt nscoding and nscopying .
. cocoa extends the c exception system
by having the primary exception response come from
the return of a zero obj {null, nil, no}
while any additional exception info is done by an nserror.out parameter .
. for telling user about error, see nsalert .
. for the complicated details
see exception programming topics for cocoa:
. that doc reminds you that the primary error reaction is by
ErrorHandlingCocoa.pdf
. see also assertions via NSAssert:
eg, NSAssert1( (0 <= component) && (component <= 255)
, @"Value %i out of range!"
, component );
. NSLog and NSLogv functions messages are written to stderr:
int recNum; NSString *recName;
NSLog( @"Record %d is %@", recNum, recName );
. sheets are a {dialog, alert, warning} attached to a specific window,
ensuring that a user never loses track of which window
the {dialog, alert, warning} belongs to.
. nstask may be the simplest way to the 2 thread cstr
(one thread is back ground) .
9.9: bk'c:
. c`realloc may entail mov's (inefficient),
plauger (p372) says that intel has no allignment req's,
[9.12: it does slow things down unless I/O-intensive]
"(async processing) is termed "(an alt to threaading ),.
threading has surprises:
avoid volatile vars in protected code
insure all exceptions are caught by each thread,
because they cannot be propagated by main program
and instead be caught by system
(which will terminate your program or thread for not handling it),
. locking has to be done at the right level (see the threading guide)
. if drawing on screen with background thread
wrap that drawing code in nsview's un/lock focus .
. mutable classes may privately mutate
globals that more than one thread is accessing
(because they are all using the cocoa framework ).
. many unix services involve shared, unprotected globals too .
. the journaling idea is the command pattern;
. NSinvocation provides it .
. composition vs subclassing is the decorator pattern .
. adde's agent system is the mvc pattern
(instead of tool running user's gui,
adde(the controller) translates communications between
{ tool(model), user(view)} .
adda's comiling to c is an adapter pattern
. reuse by giving client prferred interface .
9.9: web.addn/dev.c.intel/allignment req's on intel:
Leopard is the first Mac OS X release to really take advantage ofthe extended attributes APIs added in Tiger.The future is Objective-C, Cocoa, 64-bit.carbon is being starved .. OpenCL (letting you write simple c-style langto talk to both gpu's and multiple cores)depends on clangs jit llvm tech .. To handle task parallelism and provision threads,OpenCL is built on top of Grand Central Dispatch.
9.10: bk.addn/dev.mac/What Every Programmer Should Know About Memory(pdf):
. locality: chunks of data that are used together should be stored together,
if a node can stay within 8bytes,
it should try to get up to that size
instead of farming out the job to another node .
. the cache remembers chunks of memory called lines (64bytes),
mac file system's allocation block size (4 KB, by default)
10.6: bk"expert c:
beware namespace assumptions:
. know all the lib even if you don't use it
because their id's are reserved,
and clashing with lib names will not produce a warning
but instead cause insidiously undefined behavior!
10.11: c/shifting:
for x`shift-right n: x`shift-left n
-- x`#bits = b:
. n less than b ! -- if using shifts to mult and divide,
n`limit depends on x`size .
. x less than 0 and shifting right ?
the bits being added from the left
are impl'dep:
* arithmetic shifts preserve sign: add 1's if neg (leftmost bit = 1),
* logical shifts act the same as left shifting: add zero's .
--. to be safe and efficient,
you need to be smart about testing that x,n are in range
( test gets inside loops ).
10.9: obj'c:
. why is obj'c syntax parenthesizing declarations of a function's return type ?
because they're optional:
the default is id.type .
10.12: obj'c:
BOOL = {YES, NO}
10.13:
. using obj'c's (property,synth) syntax insures that
accessor methods are thread safe .
10.19: todo.addn/dev.mac/modular keychain:
. the firefox auto'form-filler is not complete,
and probably will never be smart eno' to know how to fill all forms,
so then there is a need to have
a context menu item for an text edit box
that should also be reachable by keyboard shortcut
which will then use shortcuts to select a secret's name
and finally will paste the secret's value
into the current text edit box .
web,pos.addn/dev.mac/browsing amazon for cocoa tutors:
. keep in mind that there are
many good tutorials out there
and reading is easy with laptop
(after getting over dread of security issues with xp:
look into image copy for xp .)
[!] pos.adda/plain old c -centric
. great opengl tutorial:
-- opengl can do everything quartz can do,
but at a lower level and perhaps slower .
proj.addn/dev.mac/quartz mailing
10.20:
. obj'c root class has a callback function
with which you can define an exception handler
for if your subclass doesn't respond to an operator;
you could delegate or log for debug .
. obj's init convention is
full-param init is only one you need to override
as other inits are defaulting versions of the main one
(the one with the most parameters) .
. obj'components can be accessable to clients (public),
to inheritors (protected from public),
to self only (private),
to any within same image (package)
-- is that meaning exec'able unit of compilation units into one image
or image of a compile unit?
. being ordered ascending returns -1 ?
try test case(0,1) = 0-1 = -1
-- ok, it's quick to subtract in order, and ordered produces a negative .
. but my intuition's view of ordered assumes
descending is a negative ordered since
ascending is the default order
just like positive is the default sign .
. beware mixing nums and unsigned (modulars)
notice char is signed on intel
but generally impl'dep .
10.22:
category is subclass:
. it can have no added instance fields;
can override functions but they're completely shadowed
(no way to call [super f] after overriding f),
. like the name category suggests,
any added functions should be defined in
only one of the class's categories at a time .
. categories -- unlike subclassing --
allow delayed implementation of methods
. categories -- also unlike subclassing --
are intrusively affecting the namespace of
the base class they are extending;
ie, the functions your category added to the base,
are available to every subsequent user of that base;
so, don't add categories to system classes;
because, other users may do the same thing,
thereby causing a name conflict .
[10.28: instead,
you can subclass a library class,
and then add categories to your own subclass]
. protocols are obj'c's name for {adt's, interfaces}
syntax:
. they are put in <...>.list
since that is the sign of the abstract
@interface [name of subclass] : [base] protocol1, protocol2, ...
. to declare,
instead of using protocol as a type name,
need x.id protocol .
. a category that goes unimpl'd
is often termed abstract or informal protocol .
10.23:
. obj'c asking float for int gives 0 even when
number might be an integer
(frac=0)
without warning it does this,
but if you need to unbox your num as particular native type,
then you should ask your num whether it happens to be that type
or whether it should be converted with a cast .
10.23: web.addn/dev.mac/reviews of dev.mac books:
Cocoa Programming Scott Anguish, Erik Buck and Don Yacktman
VermontRecipesProj.dmg
Distributed Objects (DO) :
framework that allows Objective-C objects
to send messages to each other through the network.
If the user has a password on their screen saver,then they probably will not appreciateyour screen saver compromising their security(unless ScreenSaverEngine catches this and cancels the terminate message,I'm not sure).
??
. a plug-in architecture like this
is likely not giving control to your plug-in;
rather, if you quit,
it should just display whatever it would have
had events terminated your screen saver .
pos.addn/dev.mac/cert:
. more books? read cert std online .
10.24:
. nsnumber value retrieval seems non-oop
(why need to know type to retrieve value),
but you don't need to retrieve value for
functions that inout num access .
. obj'c`s description.function is the
char.st image of your obj's value .
. the english for that is
write (the inverse of read)
the value itself is
a get, put, mov, cop, etc .
co.addn/dev.mac/Drawkit/mailing list:
You have successfully confirmed your subscription
to the Drawkit mailing list.
news.addn/dev.mac/llvm/clang is public (non-beta)!:
A major highlight of the LLVM 2.6 release is the first public release ofthe Clang compiler , which is now considered tobe production quality for C and Objective-C code on X86 targets.and can compile Objective-C code 3x faster than GCC 4.2among other major features.In addition to Clang,the LLVM project has grown a number of new LLVM sub-projects, including:This release also includes the early start of a new "llvm-mc" project,which aims to auto-generate a suite ofassembler, disassembler, and other machine code technologyfrom the LLVM target descriptions.
--
Chris Lattner
LLVM Developers Mailing List
date Fri, Oct 23, 2009 at 9:39 PM
subject [llvm-announce] LLVM 2.6 Release!
news.addn/dev.mac/obj'c sans Apple
"(
. I'm a found believer of the fact that there ismuch more than that vast Cocoa framework.Much so that I'm using my own framework,largely dirived[derived] from the core Objective-C class NSObject.- NOT the NSObject provided by Cocoa,but the original one the Objective-C library provides(the one without reference counting :) ).The absolute best resource on Cocoa is the CocoaDev wikiwww.cocoadev.com .
) .
web.addn/dev.obj'c++/what is the point of obj'c++ ?:
. just as obj'c is based on c to take advantage of that std,
c++ is the lang' of some important projects
and can be object-extended the same way c was .
. essentially you are saying that c++ object system is a morrass
and begs for the obj'c way .
. you let previous work do whatever they want,
and use c++ for just it's c-style services .
...
. this is similar to the way adda is using obj'c .
10.25:
. obj'c`string`range is (starting offset, length),
#{start: a+1, ... start+len-1} .
[classes owning their obj's]
was refering to how instances of classes
implement components that are obj' ptr's .
. they should take ownership of the value by
copying the value
-- not the ptr, unless they have some be assurance
the value try are shaving by ptr will not chg .
nor be deleted
(immutable are considered to be const's
yet can be deleted unless retained )
. another issue of ownership is that it means being able to
release self's componenets before releasing self .
. if the instance didn't alloc or copy
what its calling a component
then it can't release it .
10.26:
. the fs'mgt's "(path) includes the filename;
. a problem with high-capacity sd cards is
their address space is 32 bit -- less than 2gb .
10.27:
. if mac assigns your app a temp'dir
it assigns that same dir to every instance of your app
-- signif' if you have an app on a server
being used by multiple users .
. to make tmp'files unique per user session,
give each user a folder named after
ns`processinfo's globally unique string generator
. ns`processinfo also has some obj'c ways to
access main's cli args and the unix enviro var's .
10.28:
. {retain, release} are done auto'ly when
{add, remov}ing obj's {to, from} ns`containers;
assignments similarly create aliases;
but, you need to do your own {retain, release} unless
making a hint in the name indicating
it's got same scope of same var it's aliasing .
then do neither retain nor release,
and mem {alloc, delete} will stay balanced .
10.29:
. obj'c doesn't have to wait for auto release pool to be drained:
if you over-release the obj'
the system can dealloc before pool is drained
leaving pool with dangling ptr, causing seg'violation .
. unlike a subheap, the autorelease pool drain
doesn't take enclosed obj's away;
it simply activates any previous auto release requests
by turning them into releases (retain`decrements)
then a #retain=0 causes a call to dealloc .
. plug-in's (like screensaver),
need to be tested in both gc and non-gc modes ?
I thought apple`doc's said that app's should
be rewritten rather than try to
make them reusable in both systems
{manual mem'mgt, gc} .
. if you might be sublassed,
your methods refer to their class's generically
as [self class] .
10.30: bk"cocoa recipes:
. delegates are call-backs you define
that framework calls on certain events .
bk"xcode unleashed
-- example code is on cd
11.1: booking (Programming in Objective-C 2.0, Second Edition)
. for sure deep copying,
obj'c has {ns`data, ns`keyed.archiving}
-- that works even when a class
can't fully implement copying.protocol
due to being a container whose components
can be arbitrary objects, some of which
may not be supporting copying (vs pointer sharing ) .
11.2: news.addn/dev.mac/sources:
fruitstandsoftware.com asked:
"how can I do this from inside XCode?"
and found an AppleScript to do just that.
11.2: dev.mac/cocoa/important mvc point:
the view is not just cli vs gui
or user vs robot,
but any new device that contains status or controls of model
. the controller is a device driver
. mvc relates to .net lang-cil-mgt-platform
your choice of lang is a view
your driver or controller is mapping your lang, a view,
to the model lang, cil [common intermediate language].
. likewise,
each platform needs a driver for behaving like the model platform .
intel[machine lang] is a view,
clr [common language run-time] is a model .
. in the case of app's,
there is great reuse by
not having app be concerned with view:
instead providing generic status and control face
so that each view can write its own driver to that one face .
. the value of core data
is allowing easy conversion from your
data as described by obj'c`datatypes
to the universal descritions provided by sgml, xml,
and relational db std's .
. you interface just one core data, one model data description,
and you get controllers for a variety of other persistence views .
. IB (interface builder)'s api is
ns`view;
the connections IB makes are called bindings,
generally,
which are essential for keeping var's in sync,
eg, model with controller,
or view#slider and view#digital.readout .
. the essential job of controls
is to avoid bindings directly between model and view .
. cocoa bindings refers to the way ns`controller impl's bindings;
you can still make your own controller class
that does bindings your way .
11.3:
. document arch' shows how
controllers are needed for view and model
regardless of how named .
. there is a need for 2 controllers due to there being
3 systems needing abstract communications lines:
(view, model), and (model, persistence) .
11.7: todo.addn/dev.mac/obj'c/concept of template vs instance is important:
. need to test what c is doing
as unit containing vars is linked repeatedly but separately:
can separate programs communicate through this var? .
[12.30: from [expert c].book it appears not ]
11.9: news.addn/dev.mac/Obj-C Associated Objects:
A category is not a substitute for a subclass.
Mogenerator is a command-line tool that automates
the generation of custom subclasses. Point it at your .xcdatamodel file
and it will spew out four files per entity, two for you, two for the machine.
(From Jonathan 'Wolf' Rentzsch )
11.12: dev.mac/cocoa
. what I've been calling subheaps
are called alloc or heap zones;
or zoned alloc's or heaps .
. should reserve term "(subheaps of ..)
for refering to nested heapzones .
11.14: proj.addn/dev.mac/cfe-dev mailing list:
. cfe-dev is http://clang.llvm.org/get_involved.html
for everything else clang related
[besides patch submission/discussion]
11.15: bk"obj'c:
.a -- archive,
a static lib [called archive because it's not used often
(just link times) so it can be compressed (archived)]
.so -- shared object, a dynamically loaded lib,
11.22: bk"obj'c/blocks:
. Closure variables are marked with __block.typedef int (^IntBlock)();IntBlock downCounter(int start) {__block int i = start;return [[ ^int() { return i--; } copy] autorelease];}. useage:IntBlock f = downCounter(5);NSLog(@"%d", f());
Unlike ordinary C function definitions,their value can capture state fromtheir surrounding context.A block definition produces an opaque valuewhich contains both a reference to the code within the blockand a snapshot of the current state of local stack variablesat the time of its invocation.The block may be later invoked in the same manner as a function pointer.The block may be assigned to variables, passed to functions,and otherwise treated like a normal function pointer,although the application programmer (or the API)must use mark the block with aspecial operator (Block_copy) if it's to beused outside the scope in which it was defined.Given a block value,the code within the block can beexecuted immediately at any later timeby calling it,using the same syntax that would be used for calling a function.
No comments:
Post a Comment