For...in loop results in use of undeclared indetifier - ios

I'm still new to Objective-C (coming from a Java and C# background), and I'm implementing a plugin system for an iOS SDK I'm developing.
I've defined my plugin header (Plugin.h) as follows (the java counterpath would be an abstract class, correct me if I'm doing anything wrong here).
#protocol Plugin <NSObject>
#required
- (void)initialize;
- (NSString *) getPluginName;
- (NSString *) getVersion;
#end
I then have a method in my SDK that can be used to register plugins. The array will be an array of objects that inherit from TFTPlugin.
+ (void)registerPlugins:(NSMutableArray*) array
{
for(Plugin *plugin in array)
{
[pluginClasses addObject:plugin];
}
}
But I'm getting an error at the for loop: Use of undeclared identifier 'plugin'.
Any idea what I'm doing wrong here?
Thanks

Try this:
for(id plugin in array){
if([[plugin class] conformsToProtocol:#protocol(Plugin)]) {
[pluginClasses addObject:plugin];
}
}
The checking to see if it conforms to the protocol is optional if you know that everything you are passing in actually does.

Related

Implementing an Obj-C class in my Swift project

I'm trying to add a webshop to my app. The problem is that the webshop has provided me with an Obj-C framework and I'm only familiar with making iOS apps in Swift.
I've managed to setup an Obj-C bridging header and instantiate the webshop object.
My project looks like this:
When the shop button on my CodeDetailViewController gets tapped this function gets triggered:
#IBAction func shopButtonPressed(sender: UIButton){
let instanceOfShop : Shop = Shop()
instanceOfShop.showShop()
}
My Shop.m looks like this:
#import <Foundation/Foundation.h>
#import <FMShop/FMShop.h>
#import "Shop.h"
#implementation Shop
- (void) showShop {
//SANDBOX
FMShop* shop = [[FMShop alloc] initWithKey:#"4M7HDPAQMY68S"
storeKey:#"C8RSHBH710GK8"
buyerID:nil
sandbox:YES
controller:nil
delegate:nil];
[shop showStore:kShopViewHome ID:nil];
}
#end
The showShop function in this class gets triggered. Nothing however shows up.
The manual on how to implement this webshop is aimed at Obj-C apps. Concerning the delegate it states:
delegate: Please define a class or an interface that implements the delegates. Without such, the Store will not show. Please go to FMShopDelegate to see the supported list of methods and callbacks.
This is what I could find in the framework:
#protocol FMShopDelegate <NSObject>
#optional
-(void)shopWillAppear:(FMShop*)shop;
-(void)shopDidAppear:(FMShop*)shop;
-(void)shopWillDisappear:(FMShop*)shop;
-(void)shopDidDisappear:(FMShop*)shop;
-(void)shopProductInfo:(FMShop*)shop products:(NSArray*)productArray;
-(void)shopHistoryOrderInfo:(FMShop*)shop orders:(NSArray*)orderArray;
-(void)shopPlaceOrderSuccess:(FMShop*)shop orderID:(NSString*)orderID;
-(void)shopOrderUserCancelled:(FMShop*)shop orderID:(NSString*)orderID;
-(void)shopFailed:(FMShop*)shop error:(FMShopErrorType)error;
#end
Can anyone tell me how to connect this final method to the right delegate?
Sounds like if you don't provide a delegate when you instantiate your instance of FMShop, then the show method will not work. In your Shop.m file, you're instantiating the FMShop object with nil as the delegate parameter.
Try having an object conform to the FMShopDelegate protocol, and passing this object as the delegate parameter. You could even have your Shop object conform to the protocol itself, and pass self as the delegate if that would serve your purposes.
You could do this in Swift in a new Shop.swift file, or in the Shop.m file in Objective-C:
Swift:
class Shop: NSObject {
func showShop() {
// I'm guessing on the syntax here, Xcode will help autocomplete the correct functions
let shop = FMShop(key: KEY, storeKey: STOREKEY...)
shop.show(store: kShopViewHome, id: nil)
}
}
extension Shop: FMShopDelegate {
// Implement any of the protocol functions you want here
}
Objective-C:
#interface Shop() <FMShopDelegate> // Conform to the delegate here
#end
#implementation Shop
- (void) showShop {
//SANDBOX
FMShop* shop = [[FMShop alloc] initWithKey:#"4M7HDPAQMY68S"
storeKey:#"C8RSHBH710GK8"
buyerID:nil
sandbox:YES
controller:nil
delegate:self];
[shop showStore:kShopViewHome ID:nil];
}
// Implement any of the protocol methods here
#end
You have to use bridging header for accessing obj-c file in swift
Below is the apple doc to describe how to create & use bridging header
Apple Doc
Use bridging header in your project.
https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Get Objective-C Value in C wrapper (Unity Plugin)

I'm not familiar with Objecticve-C. I'm using it because I want to natively/correctly check if an app is installed on ios. I found the Objective-C snippet to see if an app is installed and understand needing a C-wrapper to basically have unity talk to the Objective-C script (mm file). Just don't understand how to get the C-wrapper to get the Objective-C value I have within my mm script.
// UnityPluginTest-1.mm
//
// Created by OJ on 7/13/16.
//
#import <Foundation/Foundation.h>
#interface SampleClass:NSObject
/* method declaration */
- (BOOL)isFBInstalledX;
#end
#implementation SampleClass
//Objective-C value I want
- (BOOL)isFBInstalledX {
return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"fb://"]];
}
#end
//C-wrapper that talks to Unity
extern "C"
{
bool isFBInstalled(){
// Need to get the Objective C BOOL value from above, my c# script will get this value once retrieved
//return -(Bool) isFBInstalledX value //--this doesn't work
//return ..... // I give up :(
}
}
Got the Answer! - Objective-C to UnityPlugin - App Installed Status

Objection Framework Macros with Swift

i'm trying to get the Objection Framework working with Swift (XCode 6.4).
Everything works pretty well beside the macros required for register/inject objects e.g. objection_register
I followed the approach from "Bridging Cocoalumerjack with Swift" to get the macros working with Swift but XCode always complain: Use of undeclared identifier 'initialize' when implementing objectionRegister function in ObjectionSwift.m. Since i'm not to familiar with objective-c i got stuck when looking at the Objection.h initializer methods and trying to figure out whats wrong
Thx for your help!
ObjectionSwift.h
#import <Foundation/Foundation.h>
#interface ObjectionSwift : NSObject
+ (void) objectionRegister(NSString *) name;
#endif
ObjectionSwift.m
#import "ObjectionSwift.h"
#import "Objection.h"
#implementation ObjectionSwift
+ (void) objectionRegister:(NSString *) name {
objection_register_singleton(name)
}
#end
UPDATE
I switched to Typhoon as DI Framework which provides Swift support an works pretty well.
You can use class variable:
class ListingsViewController: UIViewController
{
class var initialize: Bool
{
JSObjection.registerClass(ListingsViewController.self, scope: JSObjectionScopeNormal)
return true
}
}

Access instance variable of dumped headers (iOS)

I want to know the value of "_lastNotificationReceivedBundleIdentifier" which is an instance variable of a class. The header is dumped from iOS springboard app.
#interface SBRemoteNotificationServer : NSObject <APSConnectionDelegate> {
NSMutableDictionary* _bundleIdentifiersToClients;
NSMutableDictionary* _environmentsToConnections;
unsigned _lastPlayedAlertSound;
NSString* _lastNotificationReceivedBundleIdentifier;
}
but the following code does not work:
%hook SBRemoteNotificationServer
-(void)noteApplicationFinishedLaunching:(id)launching{
NSLog(#"identifier=%#",_lastNotificationReceivedBundleIdentifier);
%orig;
}
%end
and the compiler error is:
error: ‘_lastNotificationReceivedBundleIdentifier’ was not declared in this scope
How do I access and log this NSString?
You could probably use the objective-c runtime capabilities and take a look at the method object_getInstanceVariable(the_object, "_lastNotificationReceivedBundleIdentifier", (void**)&yourPointer);
Another solution to try is:
[self valueForKey:#"lastNotificationReceivedBundleIdentifier"];
where self is the parent object and lastNotificationReceivedBundleIdentifier is the variable name. eg same as self.lastNotificationReceivedBundleIdentifier.

how do I make an objective-c delegate for a cpp class?

I'm stuck trying to combine openGL-es (xcode openGL game template with the ogles2tools library from powervr 3.0 sdk. My problem is the line of code where I load the effect file:
/*
Load the effect.
We pass 'this' as an argument as we wish to receive callbacks as the PFX is loaded.
This is optional and supplying NULL implies that the developer will take care
of all texture loading and binding to to the Effect instead.
*/
if(m_pEffect->Load(*m_pEffectParser, "Effect", c_szPfxFile, NULL, uiUnknownUniforms, &error) != PVR_SUCCESS)
{
NSLog(#"%s",error.c_str());
return;
}
I'm supposed to pass a "this" pointer so I can receive the callbacks. The delegate method I need to implement is:
EPVRTError OGLES2IntroducingPFX::PVRTPFXOnLoadTexture(const CPVRTStringHash& TextureName, GLuint& uiHandle, unsigned int& uiFlags)
{
/*
This is an optional callback function for PVRTPFXEffect and can be used to automate
the texture loading process.
If multiple effects are to be loaded and they share textures it would be
prudent to have a caching system in place so texture memory is not wasted.
Please see OGLES2MagicLantern for an example of this.
*/
if(PVRTTextureLoadFromPVR(TextureName.String().c_str(), &uiHandle) != PVR_SUCCESS)
return PVR_FAIL;
return PVR_SUCCESS;
}
I guess the big issue for me is how do I go about providing a cpp delegate method in objective-c? I did some reading on this issue, but it seemed what I was reading was going the other way. That is, an objective-c delegate in cpp. It's pretty confusing, but here's my thought...
I create a cpp class the implements the method I need. I add that to my viewController class and pass the pointer to this cpp class in the m_pEffect->Load call. Does this seem correct?
Thanks.
P.S. Sorry if my code formatting is bad. I'm still learning.
Edit: Here's the example I found regarding mixing the objective-c and cpp. It seems really similar to what I want to do.
Update: Here's some additional info (requested by user1118321)
The CPP class which needs a delegate is CPVRTPFXEffect (PVRTPFXParserAPI.h - from powerVR SDK 3.0). I would add a link, but I'm not sure if this is allowed. Here's a link to the class header, but this version (and others on the web) did not include the pDelegate attribute for the load method. I'm assuming they are examples of a previous version. Let me know if it's okay to post this class file and I will do so.
I found a good example of what I think I'm supposed to do from reading this thread. So here's what I have so far:
My CPP delegate class...
class myCppDelegate : public PVRTPFXEffectDelegate {
public:
myCppDelegate() {};
EPVRTError PVRTPFXOnLoadTexture(const CPVRTStringHash& TextureName, GLuint& uiHandle, unsigned int& uiFlags) {
return PVR_FAIL;
};
};
My Obj-C wrapper class (just modified from the example link above)...
struct RNWrapOpaque;
#interface RNWrap : NSObject {
struct RNWrapOpaque *_cpp;
}
- (id)init;
#end
implementation...
#import "RNWrap.h"
#import "Wrap.h"
#interface RNWrap ()
#property (nonatomic, readwrite, assign) RNWrapOpaque *cpp;
#end
#implementation RNWrap
#synthesize cpp = _cpp;
struct RNWrapOpaque
{
public:
RNWrapOpaque() : wrap() {};
myCppDelegate wrap;
};
- (id)init
{
self = [super init];
if (self != nil)
{
self.cpp = new RNWrapOpaque();
}
return self;
}
- (void)dealloc
{
delete _cpp;
_cpp = NULL;
// [super dealloc];
}
#end
Basically I am able to compile the code and debug, but when the the CPVRTPFEffect class makes this call:
if(pDelegate->PVRTPFXOnLoadTexture(pTexDesc->FileName, uiHandle, uiFlags) != PVR_SUCCESS)
I get EXC_BAD_ACCESS. I'm assuming it's not finding my callback method, because I set a breakpoint and the line never gets called.
Here's my updated code which calls CPVRTPFXEffect::Load using a bridge command for the delegate parameter.
if(m_pEffect->Load(*m_pEffectParser, "Effect", c_szPfxFile,(__bridge myCppDelegate*)opaqueCppWrap, uiUnknownUniforms, &error) != PVR_SUCCESS)
Thanks for your help!
Update 2: The project uses ARC. Here's what my viewController interface looks like:
#interface ViewController : GLKViewController {
...
RNWrap* opaqueCppWrap;
...
}
#property (strong) RNWrap *opaqueCppWrap;
Adding the #property didn't help with the EXC_BAD_ACCESS. I'm not sure how to "see" the value of pDelegate when I'm tracing the CPP code. Xcode doesn't reveal anything when I hover over the variable.
I added the following line of code to the CPVRTPFXEffect::Load method (just prior to the line where it crashes):
*pReturnError += PVRTStringFromFormattedStr("Here is your class typeid: %s.\n", typeid(pDelegate).name());
return PVR_FAIL;
This is what displayed in the debug output window:
Here is your class typeid: P21PVRTPFXEffectDelegate.
I'm not sure what the "P21" means (if anything), but it looks like I'm close to getting this working. I dunno, maybe this is as close as it gets. Still crashing and not finding my method.
First, you may want to look at the last article in the series on wrapping C++. Most of it has gotten much simpler in the latest versions of clang. You probably don't need half this code anymore. ObjC++ objects can now have private C++ properties without any tricks, while maintaining a pure-ObjC interface.
Here is how you want to think about this problem:
Build a C++ object that is the delegate. Write all the code involved in setting up the delegation, etc, in C++. So when it says "pass a this pointer" you should really be passing a this pointer (because you should be doing this in the C++ code). The fact that you're doing a _bridge cast in a C++ call is a real hint something is going wrong.
Let an ObjC own the C++ object as a property.
Write the delegate callbacks in C++ inside the C++ object. If useful, you can let the C++ object then make calls into the ObjC object as needed, but it may be easier if the C++ object does all the delegate work.
I finally got this working, but had to remove the obj-c wrapper class from my viewController in order to do so. Here's what the code looks like:
ViewController.h
struct Opaque;
#interface ViewController : GLKViewController {
...
//RNWrap* opaqueCppWrap; // this didn't work
struct Opaque *opaqueCpp; // try this
...
}
ViewController.mm
// declare the Opaque structure
struct Opaque {
public:
Opaque() : cppobject() {};
myCppDelegate cppobject;
};
viewDidLoad
// ... create opaque member on initialization
opaqueCpp = new Opaque();
//opaqueCppWrap = [[RNWrap alloc] init]; // old way of doing things using wrapper
pass the delegate to the Load method
// old way using bridge cast and wrapper
//if(m_pEffect->Load(*m_pEffectParser, "Effect", c_szPfxFile,(__bridge myCppDelegate*)opaqueCppWrap, uiUnknownUniforms, &error) != PVR_SUCCESS)
// this works...
if(m_pEffect->Load(*m_pEffectParser, "Effect", c_szPfxFile, (myCppDelegate*)opaqueCpp, uiUnknownUniforms, &error) != PVR_SUCCESS)
Not sure why the wrapper class doesn't work, but I'm happy that my callback is working (appy no crashy!)
Phew, that was rough. Any thoughts/comments?

Resources