expected ';' at end of declaration list objective c - objective-c

"error: expected ';' at end of declaration list" objective c
When I am trying to declare global variable
#implementation CachingManager{
NSMutableArray*object = [[NSMutableArray alloc] init];
}

You can create instance variables here but cannot initialize those instance variables here like you do. They are all initialized to nil or zeroes. So compiler expect a semicolon when you are writing an equal sign.
You can initialize them in init method or other method where your class initialization takes place in order to make them global variables. e.g.
Interface block for instance variable inside .m file:
#interface CachingManager ()
{
// instance variables initialized to nil or zeroes
NSMutableArray *object; // global ivar
}
#end
Implementation part same .m file:
#implementation CachingManager
- (void)viewDidLoad {
[super viewDidLoad];
object = [[NSMutableArray alloc] init]; // initialization takes place
}

One way to implement global variables, and to manage their lifetime (i.e. that they are initialised) and even to provide global methods is to implement a class exposing those variables/methods and to use the singleton pattern:
yourFile.h:
#import <Foundation/Foundation.h>
#interface GlobalVars : NSObject
{
NSMutableArray *_truckBoxes;
NSMutableArray *_farmerlist;
NSString *_farmerCardNumber;
NSString *_fName;
}
+ (GlobalVars *)sharedInstance;
#property(strong, nonatomic, readwrite) NSMutableArray *truckBoxes;
#property(strong, nonatomic, readwrite) NSMutableArray *farmerList;
#property(strong, nonatomic, readwrite) NSString *farmerCardNumber;
#property(strong, nonatomic, readwrite) NSString *fName;
#end
yourFile.m:
#import "GlobalVars.h"
#implementation GlobalVars
#synthesize truckBoxes = _truckBoxes;
#synthesize farmerList = _farmerList;
#synthesize frameCardNumber = _frameCardNumber;
#synthesize fName = _fName;
+ (GlobalVars *)sharedInstance {
static dispatch_once_t onceToken;
static GlobalVars *instance = nil;
dispatch_once(&onceToken, ^{
instance = [[GlobalVars alloc] init];
});
return instance;
}
- (id)init {
self = [super init];
if (self) {
_truckBoxes = [[NSMutableArray alloc] init];
_farmerlist = [[NSMutableArray alloc] init];
// Note these aren't allocated as [[NSString alloc] init] doesn't provide a useful object
_farmerCardNumber = nil;
_fName = nil;
}
return self;
}
You can then use these global variables like this, for example:
GlobalVars *globals = [GlobalVars sharedInstance];
globals.fName = #"HelloWorld.txt";
[globals.farmerList addObject:#"Old Macdonald"];
[self processList:[globals farmerList]];
However, please consider:
You don't need to use global variables like this; you should be able to create a model object which is created as necessary and reference to it passed to the views. This is MVC.
You also posted a stack trace of an unrelated issue which is extremely common with Objective-C; only you can fix this error, once you realise what it is.

That sin't a global variable. That would be an instance variable and that particular syntax wasn't commonly used after 2005 (really, it wasn't terribly common after the mid 90s).
If you want a global variable, do:
NSMutableArray *myGlobal;
Somewhere at the top level -- at the same level with the #implementation -- of your source.
You'll have to initialize the global variable elsewhere, though. Typically, in the +initialize or +load method of the class.

Related

Cannot access Objective-C singleton's array from Swift code

I made an array in a singleton to write objects into it from multiple parts of my code. Here's how:
// in singleton.h
#import <UIKit/UIKit.h>
// make globally accessible array
#interface MyManager : NSObject {
NSMutableArray *imgArray;
}
#property (nonatomic, retain) NSMutableArray *imgArray;
+ (id)sharedManager;
#end
// in singleton.m
#import "singleton.h"
For my .m file :
#implementation MyManager
#synthesize imgArray;
#pragma mark Singleton Methods
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
- (id) init {
if (self = [super init]) {
self.imgArray = [NSMutableArray new];
}
NSLog(#"initialized");
return self;
}
#end
I can access my array called imgArray it from my objective C code. However, In swift I get an error when I do this:
let array = MyManager.sharedManager()
array.imgArray.add("hello world") . (!!!) Value of type 'Any?' has no member 'imgArray'
I can access MyManager.sharedManager(), but Why can't I access imgArray the same way as in objective C?
You should declare it as instancetype or MyManager *. E.g.
+ (MyManager *)sharedManager;
or
+ (instancetype)sharedManager;
A couple of suggestions:
The Swift convention for singleton’s is to use a class property name of shared, not a class method of sharedManager(). When you declare it in Objective-C, you might want to explicitly say that it’s a class property:
#property (class, readonly, strong) MyManager *sharedManager NS_SWIFT_NAME(shared);
This won’t change any of the Objective-C behavior, but in Swift, you can just do:
let manager = MyManager.shared
manager.images.add(image)
This results in more concise and idiomatic Swift code.
I’d suggest that you audit your Objective-C for nullability. I.e., confirm what can be nil and what can’t. Since both imgArray (which I might just call images) and sharedManager can never be nil, I would just use the NS_ASSUME_NONNULL_BEGIN/END macros which tells the compiler “unless I tell you otherwise, assuming this property cannot be nil”:
// MyManager.h
#import UIKit;
NS_ASSUME_NONNULL_BEGIN
#interface MyManager : NSObject
#property (nonatomic, strong) NSMutableArray <UIImage *> *images;
#property (class, readonly, strong) MyManager *sharedManager NS_SWIFT_NAME(shared);
#end
NS_ASSUME_NONNULL_END
By telling the compiler that these two cannot be nil, that means that you’ll have to do less unnecessary unwrapping of optionals in your Swift code.
As an aside, notice that I didn't declare an instance variable. (And if you did need one, I wouldn’t advise declaring it in the public interface.) Objective-C will now synthesize the ivars backing our properties automatically for us. (So my property images will have an ivar called _images that will be synthesized for me.) And you don’t need/want the #synthesize line, either:
// MyManager.m
#import "MyManager.h"
#implementation MyManager
+ (instancetype)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
- (instancetype)init {
if (self = [super init]) {
self.images = [NSMutableArray new];
}
NSLog(#"initialized");
return self;
}
#end
Change + (id)sharedManager; to + (MyManager *)sharedManager;. Otherwise Swift doesn't know what kind of object sharedManager is and it will assume it's Any.

How can I pass a NSString parameter to a function?

I want to initialize an object. The problem is how to pass the NSString correctly.
Object code:
#import "ClaseHoja.h"
#implementation ClaseHoja
#synthesize pares;
#synthesize nombre;
-(id)init
{
self=[super init];
if(self){
}
return self;
}
-(id)initWithValues:(NSString*)nom par:(int)par
{
if([super init]){
pares=par;
nombre=nom;
}
return self;
}
When I call the function I do this:
NSString *nombre="Hello";
int par=20;
ClaseHoja *ch = [ClaseHoja alloc] initWithValues:nombre par:numPares]];
I would suggest:
Add the missing # to #"Hello" and fix the [] in your alloc/init call.
If you're using Xcode, I'd let the compiler synthesize the properties for you. No #synthesize is needed. If you're using a stand-alone LLVM on some other platform, though, you might need it, but by convention, you'd specify an ivar with a preceding _.
I'd define nombre to be copy property and explicitly copy the nombre value passed to your init method. You don't want to risk having a NSMutableString being passed to your method and having it unwittingly mutated without your knowledge.
I'd suggest renaming the initWithValues:par: to be initWithNombre:pares:, to eliminate any doubt about what properties are being updated.
You don't need init without parameters. You can just rely on the one provided by NSObject.
You'd generally use NSInteger rather than int.
In your custom init method, you want to make sure to do if ((self = [super init])) { ... }
Thus:
// ClaseHoja.h
#import Foundation;
#interface ClaseHora: NSObject
#property (nonatomic, copy) NSString *nombre;
#property (nonatomic) NSInteger pares;
- (id)initWithNombre:(NSString*)nombre pares:(NSInteger)pares;
#end
And
// ClaseHoja.m
#import "ClaseHoja.h"
#implementation ClaseHoja
// If you're using modern Objective-C compiler (such as included with Xcode),
// you don't need these lines, but if you're using, for example stand-alone
// LLVM in Windows, you might have to uncomment the following lines:
//
// #synthesize nombre = _nombre;
// #synthesize pares = _pares;
- (id)initWithNombre:(NSString*)nombre pares:(NSInteger)pares {
if ((self = [super init])) {
_pares = pares;
_nombre = [nombre copy];
}
return self;
}
#end
And you'd use it like so:
NSString *nombre = #"Hello";
NSInteger pares = 20;
ClaseHoja *ch = [[ClaseHoja alloc] initWithNombre:nombre pares:pares];
You need to pass like this. Another thing you miss # sign before the string.
NSString *nombre = #"Hello"; int par=20;
ClaseHoja *ch = [[ClaseHoja alloc]initWithValues:nombre par:par];

Appending to an array in an object from a ViewController

I would like to append an object to an NSMutableArray in an object class from a ViewController. It's set up like bellow, but the code below does not seem to work. If I log the array from the ViewController, it appears to be appended, but if I log it from the object class, it's empty.
CaptureManager.h
#import <UIKit/UIKit.h>
#class AVCamRecorder;
#protocol CaptureManagerDelegate;
#interface CaptureManager : NSObject {
}
#property (nonatomic,strong) NSMutableArray *assets;
#end
ViewController
CaptureManager *cm = [[CaptureManager alloc] init];
cm.assets = [[NSMutableArray alloc]init];
[cm.assets addObject:asset];
Alternatively, just pass in a specific instance of CaptureManager to the VC, either through an initializer or by creating a CaptureManager property on the VC and setting it to the specific instance of CaptureManager.
You can (and should) read all about why you should avoid singleton abuse here.
It's because in your view controller you're creating a new object of CaptureManager. So you must pass a pointer of already created CaptureManager and use that, or have a shared instance (singleton) and use that in your view controllers, e.g.
#interface CaptureManager : NSObject
+ (instancetype)sharedManager;
#property (nonatomic,strong) NSMutableArray *assets;
#end
//--
#implementation
+ (instancetype)sharedManager
{
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [self new];
});
return instance;
}
- (id)init
{
self = [super init];
self.assets = [NSMutableArray new];
return self;
}
Then, in your vc:
[[CaptureManager sharedManager].assets addObject:asset];

How to init objects in Objective-C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm unsure how I should initialise the various properties in an objective-C class. Please assume I'm a very new user to Objective-C in your answers...
I have the following classes:
Test class
#interface Test : NSObject
#property (nonatomic, strong) NSString *name;
#end
TestManager class
#interface TestManager : NSObject
#property (nonatomic, strong) NSMutableArray *tests; // array of Test objects (array size unknown until runtime)
#end
Controller class
#interface TestController : NSObject
#property (nonatomic, strong) TestManager *aManager;
-(void)initManager;
-(void)doSomething;
#end
I want to have an method like initManager called:
-(void)initManager
{
// how can I init the aManager which will have an array of Test objects
}
which will automatically allocate an array of objects to be stored inside the manager class so I can do things like:
-(void)doSomething
{
NSString *name = ((Test *)[self.aManager.tests objectAtIndex:0]).name;
}
I'm not even sure that initManager is the correct method to use - is there something built in that always gets called?
Firstly, let's look at the way we can initialize your Test class objects.
You can also write some initialization method for your Test class so instead of this:
Test example = [[Test alloc] init];
example.name = #"s";
you can write something like this:
Test example = [[Test alloc] initWithName:#"s"];
Please note that this is very common for initialization method to return newly created object, hence the initialization method usually returns 'id' type (not void).
This is the implementation for your test class which will be used in examples below.
.h file:
- (id)initWithName:(NSString *)aName;
.m file:
- (id)initWithName:(NSString *)aName
{
self = [super init];
if (self) {
_name = aName;
}
return self;
}
You can initialize your TestController class this way:
.h file:
- (id)initManager;
.m file:
- (id)initManager
{
self = [super init]; //always call the superclass init method when your class inherit from other class
if (self) { // checking if the superclass initialization was fine
_tests = [NSMutableArray array];
[_tests addObject:[[Test alloc] initWithName:#"s"]];
[_tests addObject:[[Test alloc] initWithName:#"l"]];
}
return self;
}
Or something like this:
- (id)initManager
{
self = [super init]; //always call the superclass init method when your class inherit from other class
if (self) { // checking if the superclass initialization was fine
_tests = [NSArray arrayWithObjects:[[Test alloc] initWithName:#"s"], [[Test alloc] initWithName:#"l"]];
}
return self;
}
Like the #Andrew said it is better to use alloc + init. Here are some examples of this syntax:
CGRect rect = CGRectMake(0, 0, 100, 100);
[[UIView alloc] initWithFrame:rect];
[[NSArray alloc] init]
This is the common way to initialize objects. Despite having this mechanism there are also some additional methods (which are in fact static functions) which give the programmer the nice way to initialize objects. Using them u don't have to write keyword 'alloc' so that the code is shorter and easier to read.
[NSArray array] //creates and returns empty array
[NSMutableArray array] //creates and return empty mutable array
[UIButton buttonWithType:UIButtonTypeContactAdd]; //creates and return button
first import header files of test, and test manager class, into controller class
#import Test.h
#import TestManager.h
then in controller class
-(void)initManager
{
TestManager *aTestManager = [TestManager new];
Test *test1 = [Test new];
Test *test2 = [Test new];
[aTestManager.tests addObject:test1];
[aTestManager.tests addObject:test2];
}
Let's start at the top. You probably can and should make the name readonly.
(Demos assume ARC is enabled)
#interface Test : NSObject
#property (nonatomic, readonly) NSString *name;
// and then simply initialize name:
- (instancetype)initWithName:(NSString *)pName;
#end
NSString properties should be copied:
#implementation Test
- (instancetype)initWithName:(NSString *)pName
{
self = [super init];
if (nil == self) return nil;
// copy the NSString:
// don't use getters/setters in initializers or -dealloc
_name = pName.copy;
return self;
}
#end
Similarly readonly:
#interface TestManager : NSObject
#property (nonatomic, strong, readonly) NSMutableArray *tests; // array of Test objects (array size unknown until runtime)
#end
#implementation TestManager
- (id)init
{
self = [super init];
if (nil == self) return nil;
// just initialize readonly tests:
_tests = NSMutableArray.new;
return self;
}
#end
Then TestController could probably use a readonly TestManager and borrow the form used above. Otherwise, it can be readwrite, if needed.
// don't declare/implement an instance method
// which has the prefix -init*, like initManager. renamed.
- (void)resetManager
{
// if readonly is ok, then just create it in the initializer.
// otherwise, if you need the ability to set the manager in the controller,
// then declare the property readwrite and:
self.testManager = TestManager.new;
// note: aManager is not a good name. renamed to testManager.
}
- (void)doSomething
{
assert(self.testManager && "did you forget to init the manager?");
Test * test = [self.testManager.tests objectAtIndex:0];
NSString * name = test.name;
...
}
This is far from covering all initialization cases in ObjC, but it is a start.

Unable to update singleton properties

I've encountered a stupid problem, and I've tried almost everything (bought 3 books, went through the whole google :)) but nothing helped. And it seems to me like the solution should be extremely simple...
I need to declare a singleton in Objective-C (for an iOS app, if that matters), and it should have some properties that I need to update from other classes. But I can't do that - the properties just won't update, they have the same values set in the "init" method.
I've created a simple app to test out this problem. That's what I've done:
First, I've declared a sample class and its subclass that I'm going to use as a singleton's property:
#interface Entity : NSObject
#property (nonatomic, strong, readwrite) NSMutableString * name;
#end
#implementation Entity
#synthesize name;
#end
#interface Company : Entity
#property (nonatomic, strong, readwrite) NSMutableString * boss;
#property (nonatomic) int rating;
#end
#implementation Company
#synthesize boss, rating;
#end
Then I declare the singleton itself based on the method described in the "iOS Programming Guide by Big Nerd Ranch" book. I'm using both my custom class and a standard NSMutableString as properties, just for clarity's sake:
#class Company;
#interface CompanyStore : NSObject
{
NSMutableString * someName;
}
#property (nonatomic, strong, readwrite) Company * someCompany;
#property (nonatomic, strong, readwrite) NSMutableString * someName;
+ (CompanyStore *) store;
- (void) modifyCompanyProperties;
#end
#implementation CompanyStore
#synthesize someCompany, someName;
// Declaring the shared instance
+ (CompanyStore *) store
{
static CompanyStore * storeVar = nil;
if (!storeVar) storeVar = [[super allocWithZone:nil] init];
return storeVar;
}
// Replacing the standard allocWithZone method
+ (id) allocWithZone:(NSZone *)zone
{
return [self store];
}
Then I initialize all the properties with initial values:
- (id) init
{
self = [super init];
if (self) {
someCompany = [[Company alloc] init];
[someCompany setBoss:[NSMutableString stringWithFormat:#"John Smith"]];
[someCompany setName:[NSMutableString stringWithFormat:#"Megasoft"]];
[someCompany setRating:50];
someName = [[NSMutableString alloc] initWithString:#"Bobby"];
}
return self;
}
And from another class (view controller that displays the contents in a view):
1. I get the values of the singleton's properties. Everything's okay - I get "John Smith", "Megasoft", "Bobby" and 50 for my int value. The values from my init method.
2. I change the singleton's properties from that view controller (using several ways - I'm not sure now which one is right):
- (IBAction)modify2Button:(id)sender {
CompanyStore * cst = [CompanyStore store];
NSMutableString * name = [[NSMutableString alloc] initWithString:#"Microcompany"];
NSMutableString * boss = [[NSMutableString alloc] initWithString:#"Larry"];
[[[CompanyStore store] someCompany] setName:name];
cst.someCompany.boss = boss;
NSMutableString * strng = [[NSMutableString alloc] initWithString:#"Johnny"];
[cst setSomeName:strng];
}
... and then I'm trying to get the values again. I'm still getting the old set - "John Smith", "Megasoft" etc. even though when I set a breakpoint at one of the strings, I can see that singleton's name property is "Microcompany" and not "Megasoft" at the time of the break... But it doesn't seem to be assigned.
3. Then I'm trying another thing - I'm calling from the view controller a singleton's private method, which assigns another set of values to the properties. This is that method in the singleton:
- (void) modifyCompanyProperties
{
NSMutableString * boss = [[NSMutableString alloc] initWithString:#"George"];
NSMutableString * name = [[NSMutableString alloc] initWithString:#"Georgeland"];
[someCompany setBoss:boss];
[someCompany setName:name];
[someCompany setRating:100000];
[someName setString:#"Nicholas"];
}
4. I'm trying to get the updated property values from the view controller again... and still get those "John Smith", "Megasoft"... Nothing changes.
It seems like the properties of the singleton are set only once and then I can't change them, even though their attributes are declared as "readwrite".
It looks like I don't understand something simple.
If someone could explain how to correctly declare and update properties in singletons, I would be very grateful.
First thing I noticed was that you are declaring "storeVar" in the body of the store method. And this looks like terribly wrong to me because every time you call this you'll re-initialize the singleton. You should declare the variable like this:
static CompanyStore * storeVar = nil;
#implementation CompanyStore
#synthesize someCompany, someName;
// Declaring the shared instance
+ (CompanyStore *) store
{
if (!storeVar) storeVar = [[super allocWithZone:nil] init];
return storeVar;
}
Also your init method is not exactly complete because you don't want to call init again after the singleton has been initialized so you have to check this and if it has been initialized you should simply return it:
- (id) init
{
if (storeVar!=nil) {
return storeVar;
}
self = [super init];
if (self) {
someCompany = [[Company alloc] init];
[someCompany setBoss:[NSMutableString stringWithFormat:#"John Smith"]];
[someCompany setName:[NSMutableString stringWithFormat:#"Megasoft"]];
[someCompany setRating:50];
someName = [[NSMutableString alloc] initWithString:#"Bobby"];
}
return self;
}
Also, this is not a mistake, just a mere suggestion - you can ditch #synthesize because since ios 6 because the compiler generates it automatically. But again, not a mistake to use it. Hope it helps