Copy and Assign Properties

Copy and assign properties

Besides weak and strong properties you can also declare them as assign or copy.

The monatomic and atomic keywords are used in multi-threading.

You declare a property as assign if it holds a primitive value, or is a structure, so usually anything that isn’t an object.

1
2
@property (nonatomic, assign) int primitiveNumber;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

When you declare a property as copy, a copy of the object is stored instead otherwise you copy a pointer to the original object.

1
@property (nonatomic, copy) NSString *text;

This is a strong relationship, but with the newly copied object.

Making a property copy is used most often with strings and arrays to ensure that you get a unique object that cannot be changed out from under you.

Sometimes retain is used. Retain is simply a synonym for strong, and it acts in exactly the same way.

Install CLI Dropbox on to Ubuntu

This post will help you install the Linux Dropbox client on your headless Ubuntu Server and link it up to your Dropbox account. The Dropbox approach is a great solution for sharing files. If you’re a daily Dropbox user you’ll quickly get hooked on the convenience of having your servers in the same file sharing loop as all your other Dropbox connected devices!

Installing Dropbox

Start off by downloading the Linux version of Dropbox onto your server. These steps have been tested on Ubuntu Server 10.10 and 11.04.

To download the 32Bit Version

1
wget -O dropbox.tar.gz "http://www.dropbox.com/download/?plat=lnx.x86"

To download the 64Bit Version

1
wget -O dropbox.tar.gz "http://www.dropbox.com/download/?plat=lnx.x86_64"

If you unsure which version you need you can quickly check by running uname -a.

1
sudo uname -a

If the uname output has an i686 at the end you need the 32Bit version and if it has x86_64 you want the 64Bit version.

When you extract the Dropbox archive it will automatically place its files in the home directory of the the user you’re logged in as under: ~/.dropbox. You can always move these files later but its something to keep in mind.

Extract the Dropbox archive

1
tar -xzvf dropbox.tar.gz

Linking Your Server to Your Dropbox Account

Before you take the next step you’ll want to make sure your LANG environment variable is set to a value other than NULL.

Check the value of your LANG environment variable

1
printenv LANG // outputs en_US.UTF-8 on my machine

To connect the Dropbox client on your server to your Dropbox account you’ll need to copy the link it outputs into a browser window and then login to your Dropbox account.

Run dropboxd on your server

1
~/.dropbox-dist/dropboxd

It will start outputting a link similar to this one every few seconds

1
2
This client is not linked to any account...
Please visit https://www.dropbox.com/cli_link?host_id=1c1497d78b543178b9349a7c1a8b087a&cl=en_US to link this machine.

The trick to a smooth link is to make sure you leave dropboxd running while you follow the link. You don’t need to access the link from the server you’re trying to install Dropbox on. You can copy and paste that link into a browser running on a separate machine and Dropbox will authorize the client running on your server.

Once it succeeds you’ll see the message Client successfully linked, Welcome! on your server and it will stop printing the authorization link.

1
2
3
Hit ctrl c to terminate the process

Client successfully linked, Welcome!

Once the Dropbox client on your server is successfully linked it will automatically create a Dropbox folder under ~/Dropbox for the user you’re logged in as. All your folders will be visible under the Dropbox folder but since the Dropbox service isn’t actually running on your server yet you you won’t be able to see the files inside these folders until the client is running and has a check to synchronize.

You can manually start the service by running

1
~/.dropbox-dist/dropbox

However, a better option for controlling the Dropbox client is to setup an Ubuntu service management script for it.
Start Dropbox Automatically On Boot

Dropbox provides a handy little service management script that makes it easy to start, stop and check the status of the Dropbox client.

Create a new file for the service management script

1
sudo vi /etc/init.d/dropbox

Paste the following script into the new file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/sh
# dropbox service
# Replace with linux users you want to run Dropbox clients for
DROPBOX_USERS="user1 user2"

DAEMON=.dropbox-dist/dropbox

start() {
echo "Starting dropbox..."
for dbuser in $DROPBOX_USERS; do
HOMEDIR=getent passwd $dbuser | cut -d: -f6
if [ -x $HOMEDIR/$DAEMON ]; then
HOME="$HOMEDIR" start-stop-daemon -b -o -c $dbuser -S -u $dbuser -x $HOMEDIR/$DAEMON
fi
done
}

stop() {
echo "Stopping dropbox..."
for dbuser in $DROPBOX_USERS; do
HOMEDIR=getent passwd $dbuser | cut -d: -f6
if [ -x $HOMEDIR/$DAEMON ]; then
start-stop-daemon -o -c $dbuser -K -u $dbuser -x $HOMEDIR/$DAEMON
fi
done
}

status() {
for dbuser in $DROPBOX_USERS; do
dbpid=pgrep -u $dbuser dropbox
if [ -z $dbpid ] ; then
echo "dropboxd for USER $dbuser: not running."
else
echo "dropboxd for USER $dbuser: running (pid $dbpid)"
fi
done
}

case "$1" in

start)
start
;;

stop)
stop
;;

restart|reload|force-reload)
stop
start
;;

status)
status
;;

*)
echo "Usage: /etc/init.d/dropbox {start|stop|reload|force-reload|restart|status}"
exit 1

esac

exit 0

Make sure you replace the value of DROPBOX_USERS with a comma separated list of the linux users on your machine you want to run the Dropbox client to run for. Each user in the list should have a copy of the Dropbox files and folders that you extracted from the archive, available under their home directory.

Make sure the script is executable and add it to default system startup run levels

1
2
sudo chmod +x /etc/init.d/dropbox
sudo update-rc.d dropbox defaults

Control the Dropbox client like any other Ubuntu service

1
sudo service dropbox start|stop|reload|force-reload|restart|status

Depending upon the number of files you have on Dropbox and the speed of your internet connection it may take some time for the Dropbox client to synchronize everything.
Check Status with Dropbox CLI

Dropbox has a command line python script available separately to provide more functionality and details on the status of the Dropbox client.

Download the dropbox.py script and adjust the file permissions

1
2
wget -O ~/.dropbox/dropbox.py "http://www.dropbox.com/download?dl=packages/dropbox.py"
chmod 755 ~/.dropbox/dropbox.py

You can download the script anywhere you like, I’ve included it along with the rest of the Dropbox files.

Now you can easily check the status of the Dropbox client

1
2
3
~/.dropbox/dropbox.py status

Downloading 125 files (303.9 KB/sec, 1 hr left)

Get a full list of CLI commands

1
~/.dropbox/dropbox.py help

Note: use dropbox help to view usage for a specific command.

Command Action
status get current status of the dropboxd
help provide help
puburl get public url of a file in your dropbox
stop stop dropboxd
running return whether dropbox is running
start start dropboxd
filestatus get current sync status of one or more files
ls list directory contents with current sync status
autostart automatically start dropbox at login
exclude ignores/excludes a directory from syncing

Use the exclude command to keep specific files or folders from syncing to your server

1
2
3
4
5
~/.dropbox/dropbox.py help exclude

dropbox exclude [list]
dropbox exclude add [DIRECTORY] [DIRECTORY] ...
dropbox exclude remove [DIRECTORY] [DIRECTORY] ...

“list” prints a list of directories currently excluded from syncing.
“add” adds one or more directories to the exclusion list, then resynchronizes Dropbox.
“remove” removes one or more directories from the exclusion list, then resynchronizes Dropbox.
With no arguments, executes “list”.
Any specified path must be within Dropbox.

Once the Dropbox service is running and fully syncrhonized you can access all your Dropbox files and easily share files on your server with all your other Dropbox connected gadgets!

For more resources and troubleshooting tips visit the Text Based Linux Install page on the Dropbox wiki and the Dropbox forums. Happy syncing!

Outlets

An outlet is a property through which we talk to an element in the view. It is a pointer to an object. A strong pointer means the object it points to will stick around until we are done with it. A weak pointer means the object will only remain if someone else has a strong pointer to it. As soon as no more strong pointers exist pointing to an object or an object we have a weak pointer to, then that object will be released and no longer exist.

Delegates

Having spent the last 10 years bashing my head against a brick wall when it came to programming with cocoa, a lot of things are now beginning to make sense, in no small part thanks to these guys Ray Wenderlich and Matthijas Hollemans. Check out their sites for some great tutorials.

Delegates are simply an object responding to another objects method calls on it’s behalf. For example a UIViewController might be appointed as the delegate for a UITableView. Then the UITableView’s methods can be called from within the UIViewController. If it’s not set up as a delegate then you cannot do this and you’ll find it very difficult to control the UITableView, which hinders you slightly in achieving virtually anything in programming with cocoa.

Learning Objective C Part 3

Declared Properties

Declared properties are a convenience notation that are used to replace the declaration, and optionally the implementation of accessor methods.

Property declarations are included with method declarations in the class interface. The basic definition uses the @property compiler directive, followed by type information and property name. The property can also be configured with custom options to help define how the accessor methods behave. Here are a few simple property declarations.

1
2
3
@property BOOL flag;
@property (copy) NSString *nameObject; //copies the object during assignment.
@property (readonly) UIView *rootView; // Declare only a getter method.

Each readable property specifies a method with the same name as the property. Each writable property specifies an additional method of the form setPropertyName: where the first letter of the property name is capitalised.

In your class implementation, you can use the @synthesize compiler directive to ask the compiler to generate the methods according to the specification in the declaration.

1
2
3
@synthesize flag;
@synthesize nameObject;
@synthesize rootView;

You can also combine the above into a single line if required.

1
@synthesize flag, nameObject, rootView;

In simple terms properties reduce the amount of code you have to write. Because the majority of accessor methods are written in similar ways, properties reduce the need to write setter and getter methods for each property exposed in a class. Instead you specify the behavior you want using the property declaration and then synthesize getter and setter methods based on the declaration at compile time.

Strings

ObjC supports the same conventions for specifying strings as C. i.e. single characters are enclosed in single quotes, and multiple characters are enclosed in double quotes. ObjC frameworks do not usually use c style strings, and instead pass them around as NSString objects.

The NSString class provides an object wrapper that has many advantages, and as strings are used commonly objC provides shorthand notation for creating NSString objects from constant values. All you need to do is precede a normal double quoted string with the @ symbol, as shown below.

1
2
3
4
NSString *myString = @"My String";
NSString *anotherString = [NSString stringWithFormat:@"%d %@", 1, @"String"];
//Create an objective C string from a C string
NSString *fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];

Protocols

Protocols declare methods that can be implemented by any class. They are not classes themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol.

Protocols are used frequently to specify the interface for delegate objects. Below is a good way to look at the interplay between protocols, delegates and other objects.

The UIApplication class implements the required behavior of an application. Instead of making you subclass UIApplication to receive notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive these notifications and provide an appropriate response. You specify that your class conforms to, or adopts, a protocol by putting in the interface block the name of the protocol in <> after the name of the class from which it inherits. You do not have to declare the protocol methods you implement.

1
2
3
4
@interface MyClass : NSObject
{
}
@end

The declaration of a protocol look similar to that of a class interface, with the exceptions that protocols have no parent calss and they do not define instance variables. Here is a simple protocol declaration with one method.

1
2
3
@protocol MyProtocol
-(void)myProtocolMethod;
@end

In the case of many delegate protocols , adopting a protocol is simply a matter of implememting the methods defined by that protocol. Some protocols require you to state explicitly that you support that protocol, and protocols can specify both required and optional methods.

Learning Objective C Part 2

Methods and Messaging.

A class in objC can declare either instance or class methods. An instance method is a method that works on a particular instance of the class. Therefore before an instance method can be called , an instance of the class must be created to call it on. Class methods do not require an instance. More later.

A method declaration consists of the method type identifier. Which will be a + or -, a return type, signature key words and the parameter type and name information. The following line of code shows the declaration of an instance method for

1
2
insertObject:atIndex
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index

This declaration is preceded by a minus sign which declares this method an instance method. The methods name insertObject:atIndex: is derived from joining all the signature keywords, including the colons, which declare a parameter is required. If a method has no parameters you omit the colon after the first and only signature keyword. In this example two parameters are required.
When you want to call a method you do so by sending a message to an object. A message is the method signature along with the parameters the method requires. All messages are sent dynamically, therefore facilitating the polymorphic behavior of objC classes.
Messages are enclosed by square brackets []. Inside the brackets, the receiving object is on the left and the message along with any parameters required is on the right. To send the insertObject:atIndex: message to an object in myArray you would use the following.

1
[myArray insertObject:anObject atIndex:0];

To avoid using numerous local variables to store temporary results, objC allows you to nest messages. The return value for each nested message is used as a parameter, or as the target, of another message. For example you could replace any of the variables in the previous message with messages to retrieve variables. Therefore if you had an object called myAppObject that had methods for accessing the array object and the object to insert into the array, you could write the preceding example like this;

1
[[myAppObject theArray] insertObject:[myAppObject objectToInsert]atIndex:0];

ObjC also has a dot syntax method for invoking accessor methods. Accessor methods get and set the state of objects. Sometimes know as getters and setters. They typically take the form -(type)propertyName and -(void)setPropertyName:(type). With the dot syntax the previous message could be re-written as;

1
[myAppObject.theArray insertObject:[myAppObject objectToInsert] atIndex:0];

Dot syntax can also be used for assignment.

1
myAppObject.theArray = aNewArray;

Which is simply a different way of writing

1
[myAppObject setTheArray:aNewArray];

The preceding examples were all messages to instance methods. We can also send messages to the class. When messaging a class the method must be defined as a class method, not an instance method.
Class methods are usually factory methods. Used when making instances of the class or for accessing some sort of information associated with the class. The syntax is the same as for instance methods however a + sign is used for the method type identifier.
The following example shows how a class method is used as a factory method. In this case the array method is a class method on the NSArray class, and inherited by NSMutableArray that allocates and initializes a new instance of the class and returns it to your code.

1
2
3
NSMutableArray *myArray = nil;
//create a new array and assign it to myArray variable.
myArray = [NSMutableArray array];

The listing below shows an implementation of MyClass from the previous example. Like the class declaration, the class implementation is identified by two compiler directives; @implementation and @end. These provide the compiler with the information it requires to associate the methods with the class. A methods definition matches its corresponding declaration in the interface, except for the inclusion of a code block.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@implementation MyClass
-(id)initWithString:(NSString *)aName
{
self = [super init];
if (self) {
name = [aName copy];
}
return self;
}
+ (MyClass *)createMyClassWithString: (NSString *)aName
{
return [[[self alloc] initWithString:aName] autorelease];
}
@end

Learning Objective C Part 1

Relationships with C.

Objective C (objC) is a superset of C. Therefore all that is valid in C is valid in objective C. ObjC includes a syntax for defining classes and methods and other constructs for dynamic extension of classes. To learn objC I would fully recommend you have a good grounding in C programming, particularly the use of pointers and data structures, an understanding of object orientated programming (oop) would also be useful. If you do not have these prerequisites then I would strongly recommend you start there first. Many of the concepts of oop are present in objC, i.e. encapsulation, inheritance and polymorphism. There are a few differences which I will attempt to highlight as we go along.

Objc as mentioned is a superset of C, and therefore supports the same basic syntax as C. As in a C program a header files are defined along with source files to separate public declarations from the implementation of your code. ObjC headers use the following extensions.

.h are header files containing class, type, functions and constant declarations.

.m are source (or implementation) files. These can contain both objC and C code.

.mm are also source files but only need to be used if you are using c++ classes or features within your objC code.

To include header files within your source code the #import directive is used. This is like the #include in C except it ensures that the same file is never included more than once.

Classes.

As in most other oop languages, classes are a way of bundling some data, along with the actions that operate on that data. An object is an instance of it’s class which contains a unique set of data held within its instance variables which were declared by the class and also pointers to the methods of the class. An object contains only data and pointers to it’s class’s methods.

To specify a class in objC two things are arequired. The interface of the class and the implementation of the class. The interface contains the class declaration and is where the instance variables and methods are declared. This is the .h file. The implementation contains the method codings of the class. This is the .m file.

The following code shows how a class called UserDefinedClass which inherits from objC’s base class, NSObject. It begins with the @interface directive and ends with the @end directive. Following the user defined class name is a colon and then the name of the parent class. The instance variables (ivars) are declared in the next block of code and surrounded with curly braces { and }. Following on is the method declarations of the class, with each instance variable and method declaration terminated with a semi colon.

1
2
3
4
5
6
7
8
9
@interface USerDefinedClass : NSObject
{
int count;
id data;
NSString* name;
}
- (id)initWithString:(NSString*)aName;
+ (UserDefinedClass*)createMyClassWithString:(NSString*)aName;
@end

N.B. This interface only declares methods. Classes can also declare properties which we will look at later on.

ObjC supports both weak and strong typing for variables containing objects. Strongly typed include the class name in the variable declaration. Weakly typed use the type id instead. Weakly typed are used often for things such as collector classes, where the exact type of object may be unknown. You are probably used to using strongly typed languages, and think that weakly typed variables may cause issues, but they actually allow more flexibility and dynamism in objC programs.

1
2
MyClass *myobject1; //Strong typing
id myObject2; //Weak typing

Notice the ? In objC object references are pointers. The id type also implies a pointer. Though no is required when using id.

Reducing the RAM useage of MySQL

One thing I noticed when setting up the MySQL database was the amount of RAM that it was using on my server. It seems that when you install MySQL it is fully featured and set up for much bigger useage than your average webserver requires. My initial install was using over 100Mb. What we need to do reduce it is to create a configuration file that MySQL looks for when it starts up. In our initial webserver setup we don’t have one, so the MySQL database server starts with defaults.
To create this file from the command line you need to open up a command line text editor. There are a few about, nano, pico, vim etc. My preferred one is vim. Basically to create a file in vim you just need to start vim and state the file path. As MySQL looks for it’s config file called my.cnf in the /etc folder we simply type;

1
vi /etc/my.cnf

Now pressing i to start insert mode on the vi text editor we can type, or copy depending on what system you are using, the following text into our my.cnf document.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[cc lang="mysql"][mysqld]
port = 3306
socket = /var/lib/mysql/mysql.sock
skip-locking
set-variable = key_buffer=16K
set-variable = max_allowed_packet=1M
set-variable = thread_stack=64K
set-variable = table_cache=4
set-variable = sort_buffer=64K
set-variable = net_buffer_length=2K

# For low memory, InnoDB should not be used so keep skip-innodb uncommented unless required
skip-innodb

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 8M
sort_buffer_size = 8M

[myisamchk]
key_buffer = 8M
sort_buffer_size = 8M

[mysqlhotcopy]
interactive-timeout"[/cc]

Save the file from vi, by pressing Esc, then typing :wq this will write the file to /etc/my.cnf and quit the text editor.
Now we need to restart MySQL by using;

1
/etc/init.d/mysqld restart

Tada! Now your MySQL installation is consuming almost half the amount of RAM as before, whilst still offering way more features than you are ever likely going to need for a wordpress web host.
This could probably be trimmed down even more if needed, though this will do for starters.

^