I'm newish to obj-c and I have some code that works, but I'm thinking I may be leaking memory as I have two retain statements and no release statements.
In both cases if I remove the retain I get a bad access error on [btPairedDevices count]
Am I doing this right or is there a better way?
//===================================================================================================
- (id)init
{
self = [super init];
if (self) {
indexDeviceSearch = 0;
// Grab a list of paired devices
btPairedDevices = [IOBluetoothDevice pairedDevices];
[btPairedDevices retain];
}
return self;
}
//===================================================================================================
- (void) applicationDidFinishLaunching:(NSNotification *)notification
{
if(IOBluetoothValidateHardwareWithDescription(nil, nil) != kIOReturnSuccess)
{
[NSApp terminate:self];
}
NSLog(@"Application up an running");
// Start our timer looking for paired phones
timerDeviceSearch = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerDeviceSearchFired)
userInfo:nil
repeats:YES];
}
//===================================================================================================
- (void) timerDeviceSearchFired
{
// Check out the device
if (indexDeviceSearch < [btPairedDevices count])
{
IOBluetoothDevice *device = [btPairedDevices objectAtIndex:indexDeviceSearch];
if ([device deviceClassMajor] == kBluetoothDeviceClassMajorPhone)
{
// Found a phone
[self addNewDeviceIfAcceptable:device];
}
}
// Update the list of devices just in case the use
// paired something while we are running
btPairedDevices = [IOBluetoothDevice pairedDevices];
[btPairedDevices retain];
// Inc the index
indexDeviceSearch++;
if (indexDeviceSearch >= [btPairedDevices count])
indexDeviceSearch = 0;
}
//===========================================================================================================================
-(BOOL)addNewDeviceIfAcceptable:(IOBluetoothDevice*)device
{
NSEnumerator *enumerator;
IOBluetoothDevice *tmpDevice;
const BluetoothDeviceAddress *newDeviceAddress = [device getAddress];
// Allocate our array of monitored devices
if(!btMonitoredDevices)
{
btMonitoredDevices = [[NSMutableArray alloc] initWithCapacity:1];
if(!btMonitoredDevices)
return(FALSE);
[btMonitoredDevices retain];
}
// Walk the devices in the array.
enumerator = [btMonitoredDevices objectEnumerator];
if(enumerator)
{
const BluetoothDeviceAddress* tempAddress = NULL;
while((tmpDevice = [enumerator nextObject]))
{
tempAddress = [tmpDevice getAddress];
if(memcmp(newDeviceAddress, tempAddress, sizeof(BluetoothDeviceAddress)) == 0 )
{
// Already have it.
return(FALSE);
}
}
}
// Add new device to array
NSLog(@"Monitoring new device: %@", [device nameOrAddress]);
[btMonitoredDevices addObject:device];
// Return that we haven't seen it.
return(TRUE);
}